repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
24
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-10-09 08:44:51
hints_text
stringlengths
11
235k
base_commit
stringlengths
40
40
juspay/hyperswitch
juspay__hyperswitch-5368
Bug: refactor: change primary key of refund table for v2 ## Description Previously our refund table had `id` as PKey. Which needs to be changed to a composite Primary key as `(merchant_id, refund_id)`.
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 171e1cfe2e3..4b5f4a8ad49 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1099,7 +1099,7 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - refund (id) { + refund (merchant_id, refund_id) { id -> Int4, #[max_length = 64] internal_reference_id -> Varchar, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index d16ddcd6518..a2e35a6d6a9 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1097,7 +1097,7 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - refund (id) { + refund (merchant_id, refund_id) { id -> Int4, #[max_length = 64] internal_reference_id -> Varchar, diff --git a/migrations/2024-07-19-044034_change_primary_key_for_refund/down.sql b/migrations/2024-07-19-044034_change_primary_key_for_refund/down.sql new file mode 100644 index 00000000000..42faa31536f --- /dev/null +++ b/migrations/2024-07-19-044034_change_primary_key_for_refund/down.sql @@ -0,0 +1,5 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE refund DROP CONSTRAINT refund_pkey; + +ALTER TABLE refund +ADD PRIMARY KEY (id); diff --git a/migrations/2024-07-19-044034_change_primary_key_for_refund/up.sql b/migrations/2024-07-19-044034_change_primary_key_for_refund/up.sql new file mode 100644 index 00000000000..bbd6ef735da --- /dev/null +++ b/migrations/2024-07-19-044034_change_primary_key_for_refund/up.sql @@ -0,0 +1,12 @@ +-- Your SQL goes here +-- The below query will lock the refund table +-- Running this query is not necessary on higher environments +-- as the application will work fine without these queries being run +-- This query should be run after the new version of application is deployed +ALTER TABLE refund DROP CONSTRAINT refund_pkey; + +-- Use the `merchant_id, refund_id` columns as primary key +-- These are already unique, not null columns +-- So this query should not fail for not null or duplicate value reasons +ALTER TABLE refund +ADD PRIMARY KEY (merchant_id, refund_id);
2024-07-19T04:51:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Previously our Refund table had id as PKey. Which needs to be changed to a composite Primary key as (merchant_id, refund_id). ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested it by compiling the code and checking the file `query/refund.rs`, where id is nowhere being used. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
fe14336f78b15e948b10d09b197fb1d529939b5c
juspay/hyperswitch
juspay__hyperswitch-5364
Bug: [FEATURE] Sorting POC Allow sorting on amount and date in tables under Operations If user clicks on the arrow to sort information being on a page which is not the first one, we will sort the data via backend and redirect them to first page Performance POC to be done for the same
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 8433ac43d0c..eb04fe8300e 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4063,6 +4063,9 @@ pub struct PaymentListFilterConstraints { pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<String>>, + /// The order in which payments list should be sorted + #[serde(default)] + pub order: Order, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { @@ -4102,6 +4105,34 @@ pub struct AmountFilter { pub end_amount: Option<i64>, } +#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct Order { + /// The field to sort, such as Amount or Created etc. + pub on: SortOn, + /// The order in which to sort the items, either Ascending or Descending + pub by: SortBy, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum SortOn { + /// Sort by the amount field + Amount, + /// Sort by the created_at field + #[default] + Created, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum SortBy { + /// Sort in ascending order + Asc, + /// Sort in descending order + #[default] + Desc, +} + #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, )] diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 3d305656797..8033ec7706c 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -737,6 +737,7 @@ pub struct PaymentIntentListParams { pub starting_after_id: Option<String>, pub ending_before_id: Option<String>, pub limit: Option<u32>, + pub order: api_models::payments::Order, } impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints { @@ -758,6 +759,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo starting_after_id: value.starting_after, ending_before_id: value.ending_before, limit: Some(std::cmp::min(value.limit, PAYMENTS_LIST_MAX_LIMIT_V1)), + order: Default::default(), })) } } @@ -781,6 +783,7 @@ impl From<api_models::payments::TimeRange> for PaymentIntentFetchConstraints { starting_after_id: None, ending_before_id: None, limit: None, + order: Default::default(), })) } } @@ -807,6 +810,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF starting_after_id: None, ending_before_id: None, limit: Some(std::cmp::min(value.limit, PAYMENTS_LIST_MAX_LIMIT_V2)), + order: value.order, })) } } diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index ea91732631d..c8dc011b814 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -1,5 +1,5 @@ #[cfg(feature = "olap")] -use api_models::payments::AmountFilter; +use api_models::payments::{AmountFilter, Order, SortBy, SortOn}; #[cfg(feature = "olap")] use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; #[cfg(feature = "olap")] @@ -674,7 +674,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { payment_attempt_schema::table.on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)), ) .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) - .order(pi_dsl::created_at.desc()) .into_boxed(); query = match constraints { @@ -682,6 +681,25 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())) } PaymentIntentFetchConstraints::List(params) => { + query = match params.order { + Order { + on: SortOn::Amount, + by: SortBy::Asc, + } => query.order(pi_dsl::amount.asc()), + Order { + on: SortOn::Amount, + by: SortBy::Desc, + } => query.order(pi_dsl::amount.desc()), + Order { + on: SortOn::Created, + by: SortBy::Asc, + } => query.order(pi_dsl::created_at.asc()), + Order { + on: SortOn::Created, + by: SortBy::Desc, + } => query.order(pi_dsl::created_at.desc()), + }; + if let Some(limit) = params.limit { query = query.limit(limit.into()); }
2024-07-21T23:14:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Support sort criterial for payments list: - sort on basis of amount (ascending or descending) - sort on basis of created at time (ascending or descending) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#5364](https://github.com/juspay/hyperswitch/issues/5364) ## How did you test it? Use the curl to sort the list by following order. Order takes `on` (the field which need to be considered) and `by`( ascending or descending) ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "order": { "on": "created", "by": "asc" } }' ``` Or ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "order": { "on": "amount", "by": "desc" } }' ``` Response, here the payments will be sorted in decreasing order of amount: ``` { "count": 2, "total_count": 2, "data": [ { "payment_id": "pay_gBlmx0AlNp55baW0ATDt", "merchant_id": "merchant_1721657037", "status": "succeeded", "amount": 7000, "net_amount": 0, "amount_capturable": 7000, "amount_received": null, "connector": "stripe", "client_secret": "pay_gBlmx0AlNp55baW0ATDt_secret_Ay9Hs88sJ24Md4CRkL0v", "created": "2024-07-23T09:32:56.212Z", "currency": "EUR", "customer_id": "uiuiuiui", "customer": { "id": "uiuiuiui", "name": null, "email": "guest@ehjhjxample.com", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0003", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": null, "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "NL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "example@example.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "pi_3Pff5ZD5R7gDAGff0gTXIJJX", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_YbnmkkPd2qkewT96ujee", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_f3JtTVYi3pElw14sKngo", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null }, { "payment_id": "pay_SqPYBFChdnejflFdVXm0", "merchant_id": "merchant_1721657037", "status": "succeeded", "amount": 6540, "net_amount": 0, "amount_capturable": 6540, "amount_received": null, "connector": "stripe", "client_secret": "pay_SqPYBFChdnejflFdVXm0_secret_VTAtKjSlI7fnCEICo9v3", "created": "2024-07-22T14:12:15.554Z", "currency": "EUR", "customer_id": "uiuiuiui", "customer": { "id": "uiuiuiui", "name": null, "email": "guest@ehjhjxample.com", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0003", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": null, "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "NL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "example@example.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "pi_3PfMyLD5R7gDAGff1mamZiPY", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_YbnmkkPd2qkewT96ujee", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_f3JtTVYi3pElw14sKngo", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
074e90c9f9fbc26255ed27400a6a781aa6958339
juspay/hyperswitch
juspay__hyperswitch-5359
Bug: refactor: reframe blocklist primary key for v2 ## Description Previously our Blocklist table had `id` as PKey. Which needs to be changed to a composite Primary key as `(merchant_id, fingerprint_id)`.
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index a5185dc6076..1242368404a 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -128,7 +128,7 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - blocklist (id) { + blocklist (merchant_id, fingerprint_id) { id -> Int4, #[max_length = 64] merchant_id -> Varchar, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index da8729cf835..e66e62467db 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -128,7 +128,7 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - blocklist (id) { + blocklist (merchant_id, fingerprint_id) { id -> Int4, #[max_length = 64] merchant_id -> Varchar, diff --git a/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/down.sql b/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/down.sql new file mode 100644 index 00000000000..9600ce5addf --- /dev/null +++ b/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/down.sql @@ -0,0 +1,5 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE blocklist DROP CONSTRAINT blocklist_pkey; + +ALTER TABLE blocklist +ADD PRIMARY KEY (id); diff --git a/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/up.sql b/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/up.sql new file mode 100644 index 00000000000..c0df6d6345c --- /dev/null +++ b/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/up.sql @@ -0,0 +1,12 @@ +-- Your SQL goes here +-- The below query will lock the blocklist table +-- Running this query is not necessary on higher environments +-- as the application will work fine without these queries being run +-- This query should be run after the new version of application is deployed +ALTER TABLE blocklist DROP CONSTRAINT blocklist_pkey; + +-- Use the `merchant_id, fingerprint_id` columns as primary key +-- These are already unique, not null columns +-- So this query should not fail for not null or duplicate value reasons +ALTER TABLE blocklist +ADD PRIMARY KEY (merchant_id, fingerprint_id);
2024-07-17T18:41:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Previously our Blocklist table had `id` as PKey. Which needs to be changed to a composite Primary key as `(merchant_id, fingerprint_id)`. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Required for V2 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested it by running the blocklist Apis, which is performing fine as the id field was no where being used. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
67bfb1cfecd4a4ad8503eaf57837073bb1980bdd
juspay/hyperswitch
juspay__hyperswitch-5360
Bug: [fix] add offset and limit parameters to key transfer API
diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index d2d3604661f..6593e5d6eb0 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -3,7 +3,7 @@ use std::{fmt::Display, str::FromStr}; use common_utils::{ errors::{CustomResult, ErrorSwitch, ParsingError}, events::{ApiEventMetric, ApiEventsType}, - impl_misc_api_event_type, + impl_api_event_type, }; use error_stack::{report, Report, ResultExt}; @@ -150,4 +150,4 @@ impl ErrorSwitch<AnalyticsError> for FiltersError { } } -impl_misc_api_event_type!(AnalyticsDomain); +impl_api_event_type!(Miscellaneous, (AnalyticsDomain)); diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 853f4308b17..3e90a48ff0b 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1053,6 +1053,16 @@ pub struct ToggleKVResponse { pub kv_enabled: bool, } +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct MerchantKeyTransferRequest { + /// Offset for merchant account + #[schema(example = 32)] + pub from: u32, + /// Limit for merchant account + #[schema(example = 32)] + pub limit: u32, +} + #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct TransferKeyResponse { /// The identifier for the Merchant Account diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 3757dd98d78..32cdd83eb9f 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -16,7 +16,7 @@ pub mod user_role; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, - impl_misc_api_event_type, + impl_api_event_type, }; #[allow(unused_imports)] @@ -33,6 +33,7 @@ use crate::{ mandates::*, payment_methods::*, payments::*, + user::{UserKeyTransferRequest, UserTransferKeyResponse}, verifications::*, }; @@ -56,87 +57,102 @@ impl ApiEventMetric for PaymentIntentFiltersResponse { } } -impl_misc_api_event_type!( - PaymentMethodId, - PaymentMethodCreate, - PaymentLinkInitiateRequest, - RetrievePaymentLinkResponse, - MandateListConstraints, - CreateFileResponse, - MerchantConnectorResponse, - MerchantConnectorId, - MandateResponse, - MandateRevokedResponse, - RetrievePaymentLinkRequest, - PaymentLinkListConstraints, - MandateId, - DisputeListConstraints, - RetrieveApiKeyResponse, - BusinessProfileResponse, - BusinessProfileUpdate, - BusinessProfileCreate, - RevokeApiKeyResponse, - ToggleKVResponse, - ToggleKVRequest, - ToggleAllKVRequest, - ToggleAllKVResponse, - TransferKeyResponse, - MerchantAccountDeleteResponse, - MerchantAccountUpdate, - CardInfoResponse, - CreateApiKeyResponse, - CreateApiKeyRequest, - MerchantConnectorDeleteResponse, - MerchantConnectorUpdate, - MerchantConnectorCreate, - MerchantId, - CardsInfoRequest, - MerchantAccountResponse, - MerchantAccountListRequest, - MerchantAccountCreate, - PaymentsSessionRequest, - ApplepayMerchantVerificationRequest, - ApplepayMerchantResponse, - ApplepayVerifiedDomainsResponse, - UpdateApiKeyRequest, - GetApiEventFiltersRequest, - ApiEventFiltersResponse, - GetInfoResponse, - GetPaymentMetricRequest, - GetRefundMetricRequest, - GetActivePaymentsMetricRequest, - GetSdkEventMetricRequest, - GetAuthEventMetricRequest, - GetPaymentFiltersRequest, - PaymentFiltersResponse, - GetRefundFilterRequest, - RefundFiltersResponse, - GetSdkEventFiltersRequest, - SdkEventFiltersResponse, - ApiLogsRequest, - GetApiEventMetricRequest, - SdkEventsRequest, - ReportRequest, - ConnectorEventsRequest, - OutgoingWebhookLogsRequest, - GetGlobalSearchRequest, - GetSearchRequest, - GetSearchResponse, - GetSearchRequestWithIndex, - GetDisputeFilterRequest, - DisputeFiltersResponse, - GetDisputeMetricRequest +impl_api_event_type!( + Miscellaneous, + ( + PaymentMethodId, + PaymentMethodCreate, + PaymentLinkInitiateRequest, + RetrievePaymentLinkResponse, + MandateListConstraints, + CreateFileResponse, + MerchantConnectorResponse, + MerchantConnectorId, + MandateResponse, + MandateRevokedResponse, + RetrievePaymentLinkRequest, + PaymentLinkListConstraints, + MandateId, + DisputeListConstraints, + RetrieveApiKeyResponse, + BusinessProfileResponse, + BusinessProfileUpdate, + BusinessProfileCreate, + RevokeApiKeyResponse, + ToggleKVResponse, + ToggleKVRequest, + ToggleAllKVRequest, + ToggleAllKVResponse, + MerchantAccountDeleteResponse, + MerchantAccountUpdate, + CardInfoResponse, + CreateApiKeyResponse, + CreateApiKeyRequest, + MerchantConnectorDeleteResponse, + MerchantConnectorUpdate, + MerchantConnectorCreate, + MerchantId, + CardsInfoRequest, + MerchantAccountResponse, + MerchantAccountListRequest, + MerchantAccountCreate, + PaymentsSessionRequest, + ApplepayMerchantVerificationRequest, + ApplepayMerchantResponse, + ApplepayVerifiedDomainsResponse, + UpdateApiKeyRequest, + GetApiEventFiltersRequest, + ApiEventFiltersResponse, + GetInfoResponse, + GetPaymentMetricRequest, + GetRefundMetricRequest, + GetActivePaymentsMetricRequest, + GetSdkEventMetricRequest, + GetAuthEventMetricRequest, + GetPaymentFiltersRequest, + PaymentFiltersResponse, + GetRefundFilterRequest, + RefundFiltersResponse, + GetSdkEventFiltersRequest, + SdkEventFiltersResponse, + ApiLogsRequest, + GetApiEventMetricRequest, + SdkEventsRequest, + ReportRequest, + ConnectorEventsRequest, + OutgoingWebhookLogsRequest, + GetGlobalSearchRequest, + GetSearchRequest, + GetSearchResponse, + GetSearchRequestWithIndex, + GetDisputeFilterRequest, + DisputeFiltersResponse, + GetDisputeMetricRequest + ) +); + +impl_api_event_type!( + Keymanager, + ( + TransferKeyResponse, + MerchantKeyTransferRequest, + UserKeyTransferRequest, + UserTransferKeyResponse + ) ); #[cfg(feature = "stripe")] -impl_misc_api_event_type!( - StripeSetupIntentResponse, - StripeRefundResponse, - StripePaymentIntentListResponse, - StripePaymentIntentResponse, - CustomerDeleteResponse, - CustomerPaymentMethodListResponse, - CreateCustomerResponse +impl_api_event_type!( + Miscellaneous, + ( + StripeSetupIntentResponse, + StripeRefundResponse, + StripePaymentIntentListResponse, + StripePaymentIntentResponse, + CustomerDeleteResponse, + CustomerPaymentMethodListResponse, + CreateCustomerResponse + ) ); impl<T> ApiEventMetric for MetricsResponse<T> { diff --git a/crates/api_models/src/events/connector_onboarding.rs b/crates/api_models/src/events/connector_onboarding.rs index 0da89f61da7..c7fc2cd7de7 100644 --- a/crates/api_models/src/events/connector_onboarding.rs +++ b/crates/api_models/src/events/connector_onboarding.rs @@ -5,10 +5,13 @@ use crate::connector_onboarding::{ ResetTrackingIdRequest, }; -common_utils::impl_misc_api_event_type!( - ActionUrlRequest, - ActionUrlResponse, - OnboardingSyncRequest, - OnboardingStatus, - ResetTrackingIdRequest +common_utils::impl_api_event_type!( + Miscellaneous, + ( + ActionUrlRequest, + ActionUrlResponse, + OnboardingSyncRequest, + OnboardingStatus, + ResetTrackingIdRequest + ) ); diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index b8c893ae25d..862c361d465 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -20,7 +20,7 @@ use crate::user::{ SsoSignInRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, - UserTransferKeyResponse, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -46,48 +46,50 @@ impl<T> ApiEventMetric for TokenOrPayloadResponse<T> { } } -common_utils::impl_misc_api_event_type!( - SignUpRequest, - SignUpWithMerchantIdRequest, - ChangePasswordRequest, - GetMultipleMetaDataPayload, - GetMetaDataResponse, - GetMetaDataRequest, - SetMetaDataRequest, - SwitchMerchantIdRequest, - CreateInternalUserRequest, - UserMerchantCreate, - ListUsersResponse, - AuthorizeResponse, - ConnectAccountRequest, - ForgotPasswordRequest, - ResetPasswordRequest, - RotatePasswordRequest, - InviteUserRequest, - ReInviteUserRequest, - VerifyEmailRequest, - SendVerifyEmailRequest, - AcceptInviteFromEmailRequest, - SignInResponse, - UpdateUserAccountDetailsRequest, - GetUserDetailsResponse, - GetUserRoleDetailsRequest, - GetUserRoleDetailsResponse, - TokenResponse, - TwoFactorAuthStatusResponse, - UserFromEmailRequest, - BeginTotpResponse, - VerifyRecoveryCodeRequest, - VerifyTotpRequest, - RecoveryCodes, - GetUserAuthenticationMethodsRequest, - CreateUserAuthenticationMethodRequest, - UpdateUserAuthenticationMethodRequest, - GetSsoAuthUrlRequest, - SsoSignInRequest, - UserTransferKeyResponse, - AuthSelectRequest +common_utils::impl_api_event_type!( + Miscellaneous, + ( + SignUpRequest, + SignUpWithMerchantIdRequest, + ChangePasswordRequest, + GetMultipleMetaDataPayload, + GetMetaDataResponse, + GetMetaDataRequest, + SetMetaDataRequest, + SwitchMerchantIdRequest, + CreateInternalUserRequest, + UserMerchantCreate, + ListUsersResponse, + AuthorizeResponse, + ConnectAccountRequest, + ForgotPasswordRequest, + ResetPasswordRequest, + RotatePasswordRequest, + InviteUserRequest, + ReInviteUserRequest, + VerifyEmailRequest, + SendVerifyEmailRequest, + AcceptInviteFromEmailRequest, + SignInResponse, + UpdateUserAccountDetailsRequest, + GetUserDetailsResponse, + GetUserRoleDetailsRequest, + GetUserRoleDetailsResponse, + TokenResponse, + TwoFactorAuthStatusResponse, + UserFromEmailRequest, + BeginTotpResponse, + VerifyRecoveryCodeRequest, + VerifyTotpRequest, + RecoveryCodes, + GetUserAuthenticationMethodsRequest, + CreateUserAuthenticationMethodRequest, + UpdateUserAuthenticationMethodRequest, + GetSsoAuthUrlRequest, + SsoSignInRequest, + AuthSelectRequest + ) ); #[cfg(feature = "dummy_connector")] -common_utils::impl_misc_api_event_type!(SampleDataRequest); +common_utils::impl_api_event_type!(Miscellaneous, (SampleDataRequest)); diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index 34375a22848..7e8eaf17e30 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -10,19 +10,22 @@ use crate::user_role::{ MerchantSelectRequest, TransferOrgOwnershipRequest, UpdateUserRoleRequest, }; -common_utils::impl_misc_api_event_type!( - RoleInfoWithPermissionsResponse, - GetRoleRequest, - AuthorizationInfoResponse, - UpdateUserRoleRequest, - MerchantSelectRequest, - AcceptInvitationRequest, - DeleteUserRoleRequest, - TransferOrgOwnershipRequest, - CreateRoleRequest, - UpdateRoleRequest, - ListRolesResponse, - RoleInfoResponse, - GetRoleFromTokenResponse, - RoleInfoWithGroupsResponse +common_utils::impl_api_event_type!( + Miscellaneous, + ( + RoleInfoWithPermissionsResponse, + GetRoleRequest, + AuthorizationInfoResponse, + UpdateUserRoleRequest, + MerchantSelectRequest, + AcceptInvitationRequest, + DeleteUserRoleRequest, + TransferOrgOwnershipRequest, + CreateRoleRequest, + UpdateRoleRequest, + ListRolesResponse, + RoleInfoResponse, + GetRoleFromTokenResponse, + RoleInfoWithGroupsResponse + ) ); diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs index 7044bd8d335..4a1c8eaa31b 100644 --- a/crates/api_models/src/pm_auth.rs +++ b/crates/api_models/src/pm_auth.rs @@ -1,7 +1,7 @@ use common_enums::{PaymentMethod, PaymentMethodType}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, - impl_misc_api_event_type, + impl_api_event_type, }; #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] @@ -49,9 +49,12 @@ pub struct PaymentMethodAuthConnectorChoice { pub mca_id: String, } -impl_misc_api_event_type!( - LinkTokenCreateRequest, - LinkTokenCreateResponse, - ExchangeTokenCreateRequest, - ExchangeTokenCreateResponse +impl_api_event_type!( + Miscellaneous, + ( + LinkTokenCreateRequest, + LinkTokenCreateResponse, + ExchangeTokenCreateRequest, + ExchangeTokenCreateResponse + ) ); diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 7c0b21f9679..2f3d29c0b89 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -380,6 +380,12 @@ pub struct AuthSelectRequest { pub id: Option<String>, } +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct UserKeyTransferRequest { + pub from: u32, + pub limit: u32, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserTransferKeyResponse { pub total_transferred: usize, diff --git a/crates/api_models/src/verify_connector.rs b/crates/api_models/src/verify_connector.rs index 1db5a19a030..0e415c35229 100644 --- a/crates/api_models/src/verify_connector.rs +++ b/crates/api_models/src/verify_connector.rs @@ -8,4 +8,4 @@ pub struct VerifyConnectorRequest { pub connector_account_details: admin::ConnectorAuthType, } -common_utils::impl_misc_api_event_type!(VerifyConnectorRequest); +common_utils::impl_api_event_type!(Miscellaneous, (VerifyConnectorRequest)); diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 3e3a0da4cab..b2420709a77 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -49,6 +49,7 @@ pub enum ApiEventsType { Gsm, // TODO: This has to be removed once the corresponding apiEventTypes are created Miscellaneous, + Keymanager, RustLocker, ApplePayCertificatesMigration, FraudCheck, @@ -88,23 +89,26 @@ impl<T> ApiEventMetric for Vec<T> { } #[macro_export] -macro_rules! impl_misc_api_event_type { - ($($type:ty),+) => { +macro_rules! impl_api_event_type { + ($event: ident, ($($type:ty),+))=> { $( impl ApiEventMetric for $type { fn get_api_event_type(&self) -> Option<ApiEventsType> { - Some(ApiEventsType::Miscellaneous) + Some(ApiEventsType::$event) } } )+ }; } -impl_misc_api_event_type!( - String, - (&String, &String), - (Option<i64>, Option<i64>, String), - bool +impl_api_event_type!( + Miscellaneous, + ( + String, + (&String, &String), + (Option<i64>, Option<i64>, String), + bool + ) ); impl<T: ApiEventMetric> ApiEventMetric for &T { diff --git a/crates/diesel_models/src/query/merchant_key_store.rs b/crates/diesel_models/src/query/merchant_key_store.rs index fc4d09c4989..4e8e4637678 100644 --- a/crates/diesel_models/src/query/merchant_key_store.rs +++ b/crates/diesel_models/src/query/merchant_key_store.rs @@ -55,7 +55,11 @@ impl MerchantKeyStore { .await } - pub async fn list_all_key_stores(conn: &PgPooledConn) -> StorageResult<Vec<Self>> { + pub async fn list_all_key_stores( + conn: &PgPooledConn, + from: u32, + limit: u32, + ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, @@ -64,8 +68,8 @@ impl MerchantKeyStore { >( conn, dsl::merchant_id.ne_all(vec!["".to_string()]), - None, - None, + Some(limit.into()), + Some(from.into()), None, ) .await diff --git a/crates/diesel_models/src/query/user_key_store.rs b/crates/diesel_models/src/query/user_key_store.rs index 5aad28bb562..78d1648b470 100644 --- a/crates/diesel_models/src/query/user_key_store.rs +++ b/crates/diesel_models/src/query/user_key_store.rs @@ -14,7 +14,11 @@ impl UserKeyStoreNew { } impl UserKeyStore { - pub async fn get_all_user_key_stores(conn: &PgPooledConn) -> StorageResult<Vec<Self>> { + pub async fn get_all_user_key_stores( + conn: &PgPooledConn, + from: u32, + limit: u32, + ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, @@ -23,8 +27,8 @@ impl UserKeyStore { >( conn, dsl::user_id.ne_all(vec!["".to_string()]), - None, - None, + Some(limit.into()), + Some(from.into()), None, ) .await diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs index 07d9337e450..39f3f04c548 100644 --- a/crates/hyperswitch_domain_models/src/api.rs +++ b/crates/hyperswitch_domain_models/src/api.rs @@ -2,7 +2,7 @@ use std::{collections::HashSet, fmt::Display}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, - impl_misc_api_event_type, + impl_api_event_type, }; #[derive(Debug, Eq, PartialEq)] @@ -28,7 +28,7 @@ impl<T: ApiEventMetric> ApiEventMetric for ApplicationResponse<T> { } } -impl_misc_api_event_type!(PaymentLinkFormData, GenericLinkFormData); +impl_api_event_type!(Miscellaneous, (PaymentLinkFormData, GenericLinkFormData)); #[derive(Debug, Eq, PartialEq)] pub struct RedirectionFormData { diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs index ed36ad59aec..ba739079169 100644 --- a/crates/hyperswitch_domain_models/src/type_encryption.rs +++ b/crates/hyperswitch_domain_models/src/type_encryption.rs @@ -7,792 +7,806 @@ use common_utils::{ metrics::utils::record_operation_time, types::keymanager::{Identifier, KeyManagerState}, }; -use error_stack::ResultExt; -use masking::{PeekInterface, Secret}; -use router_env::{instrument, tracing}; +use encrypt::TypeEncryption; +use masking::Secret; use rustc_hash::FxHashMap; -#[cfg(feature = "encryption_service")] -use { - common_utils::{ - keymanager::call_encryption_service, - transformers::{ForeignFrom, ForeignTryFrom}, - types::keymanager::{ - BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse, - DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, - TransientBatchDecryptDataRequest, TransientDecryptDataRequest, - }, - }, - http::Method, - router_env::logger, -}; -#[async_trait] -pub trait TypeEncryption< - T, - V: crypto::EncodeMessage + crypto::DecodeMessage, - S: masking::Strategy<T>, ->: Sized -{ - async fn encrypt_via_api( - state: &KeyManagerState, - masked_data: Secret<T, S>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError>; - - async fn decrypt_via_api( - state: &KeyManagerState, - encrypted_data: Encryption, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError>; - - async fn encrypt( - masked_data: Secret<T, S>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError>; - - async fn decrypt( - encrypted_data: Encryption, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError>; - - async fn batch_encrypt_via_api( - state: &KeyManagerState, - masked_data: FxHashMap<String, Secret<T, S>>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; - - async fn batch_decrypt_via_api( - state: &KeyManagerState, - encrypted_data: FxHashMap<String, Encryption>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; - - async fn batch_encrypt( - masked_data: FxHashMap<String, Secret<T, S>>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; - - async fn batch_decrypt( - encrypted_data: FxHashMap<String, Encryption>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; -} +mod encrypt { + use async_trait::async_trait; + use common_utils::{ + crypto, + encryption::Encryption, + errors::{self, CustomResult}, + types::keymanager::{Identifier, KeyManagerState}, + }; + use error_stack::ResultExt; + use masking::{PeekInterface, Secret}; + use router_env::{instrument, tracing}; + use rustc_hash::FxHashMap; + #[cfg(feature = "encryption_service")] + use { + common_utils::{ + keymanager::call_encryption_service, + transformers::{ForeignFrom, ForeignTryFrom}, + types::keymanager::{ + BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse, + DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, + TransientBatchDecryptDataRequest, TransientDecryptDataRequest, + }, + }, + http::Method, + router_env::logger, + }; + + use super::metrics; + + #[async_trait] + pub trait TypeEncryption< + T, + V: crypto::EncodeMessage + crypto::DecodeMessage, + S: masking::Strategy<T>, + >: Sized + { + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<T, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError>; + + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError>; + + async fn encrypt( + masked_data: Secret<T, S>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError>; + + async fn decrypt( + encrypted_data: Encryption, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError>; + + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<T, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<T, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + } -#[async_trait] -impl< - V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<String> + Send + Sync, - > TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>> -{ - #[instrument(skip_all)] - #[allow(unused_variables)] - async fn encrypt_via_api( - state: &KeyManagerState, - masked_data: Secret<String, S>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::encrypt(masked_data, key, crypt_algo).await - } - #[cfg(feature = "encryption_service")] - { - let result: Result< - EncryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/encrypt", - EncryptDataRequest::from((masked_data.clone(), identifier)), - ) - .await; - match result { - Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), - Err(err) => { - logger::error!("Encryption error {:?}", err); - metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Encryption"); - Self::encrypt(masked_data, key, crypt_algo).await + #[async_trait] + impl< + V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, + S: masking::Strategy<String> + Send + Sync, + > TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>> + { + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<String, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } } } } - } - #[instrument(skip_all)] - #[allow(unused_variables)] - async fn decrypt_via_api( - state: &KeyManagerState, - encrypted_data: Encryption, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::decrypt(encrypted_data, key, crypt_algo).await - } - #[cfg(feature = "encryption_service")] - { - let result: Result< - DecryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/decrypt", - TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), - ) - .await; - let decrypted = match result { - Ok(decrypted_data) => { - ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) - } - Err(err) => { - logger::error!("Decryption error {:?}", err); - Err(err.change_context(errors::CryptoError::DecodingFailed)) - } - }; - - match decrypted { - Ok(de) => Ok(de), - Err(_) => { - metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Decryption"); - Self::decrypt(encrypted_data, key, crypt_algo).await + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } } } } - } - - async fn encrypt( - masked_data: Secret<String, S>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?; - Ok(Self::new(masked_data, encrypted_data.into())) - } - async fn decrypt( - encrypted_data: Encryption, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - let encrypted = encrypted_data.into_inner(); - let data = crypt_algo.decode_message(key, encrypted.clone())?; + async fn encrypt( + masked_data: Secret<String, S>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?; + Ok(Self::new(masked_data, encrypted_data.into())) + } - let value: String = std::str::from_utf8(&data) - .change_context(errors::CryptoError::DecodingFailed)? - .to_string(); + async fn decrypt( + encrypted_data: Encryption, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + let encrypted = encrypted_data.into_inner(); + let data = crypt_algo.decode_message(key, encrypted.clone())?; - Ok(Self::new(value.into(), encrypted)) - } + let value: String = std::str::from_utf8(&data) + .change_context(errors::CryptoError::DecodingFailed)? + .to_string(); - #[allow(unused_variables)] - async fn batch_encrypt_via_api( - state: &KeyManagerState, - masked_data: FxHashMap<String, Secret<String, S>>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::batch_encrypt(masked_data, key, crypt_algo).await + Ok(Self::new(value.into(), encrypted)) } - #[cfg(feature = "encryption_service")] - { - let result: Result< - BatchEncryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/encrypt", - BatchEncryptDataRequest::from((masked_data.clone(), identifier)), - ) - .await; - match result { - Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), - Err(err) => { - metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::error!("Encryption error {:?}", err); - logger::info!("Fall back to Application Encryption"); - Self::batch_encrypt(masked_data, key, crypt_algo).await + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<String, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } } } } - } - #[allow(unused_variables)] - async fn batch_decrypt_via_api( - state: &KeyManagerState, - encrypted_data: FxHashMap<String, Encryption>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::batch_decrypt(encrypted_data, key, crypt_algo).await - } + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } - #[cfg(feature = "encryption_service")] - { - let result: Result< - BatchDecryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/decrypt", - TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), - ) - .await; - let decrypted = match result { - Ok(decrypted_data) => { - ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) - } - Err(err) => { - logger::error!("Decryption error {:?}", err); - Err(err.change_context(errors::CryptoError::DecodingFailed)) - } - }; - match decrypted { - Ok(de) => Ok(de), - Err(_) => { - metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Decryption"); - Self::batch_decrypt(encrypted_data, key, crypt_algo).await + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } } } } - } - async fn batch_encrypt( - masked_data: FxHashMap<String, Secret<String, S>>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - masked_data - .into_iter() - .map(|(k, v)| { - Ok(( - k, - Self::new( - v.clone(), - crypt_algo.encode_message(key, v.peek().as_bytes())?.into(), - ), - )) - }) - .collect() - } + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<String, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new( + v.clone(), + crypt_algo.encode_message(key, v.peek().as_bytes())?.into(), + ), + )) + }) + .collect() + } - async fn batch_decrypt( - encrypted_data: FxHashMap<String, Encryption>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - encrypted_data - .into_iter() - .map(|(k, v)| { - let data = crypt_algo.decode_message(key, v.clone().into_inner())?; - let value: String = std::str::from_utf8(&data) - .change_context(errors::CryptoError::DecodingFailed)? - .to_string(); - Ok((k, Self::new(value.into(), v.into_inner()))) - }) - .collect() + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + let data = crypt_algo.decode_message(key, v.clone().into_inner())?; + let value: String = std::str::from_utf8(&data) + .change_context(errors::CryptoError::DecodingFailed)? + .to_string(); + Ok((k, Self::new(value.into(), v.into_inner()))) + }) + .collect() + } } -} -#[async_trait] -impl< - V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<serde_json::Value> + Send + Sync, - > TypeEncryption<serde_json::Value, V, S> - for crypto::Encryptable<Secret<serde_json::Value, S>> -{ - #[instrument(skip_all)] - #[allow(unused_variables)] - async fn encrypt_via_api( - state: &KeyManagerState, - masked_data: Secret<serde_json::Value, S>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::encrypt(masked_data, key, crypt_algo).await - } - #[cfg(feature = "encryption_service")] - { - let result: Result< - EncryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/encrypt", - EncryptDataRequest::from((masked_data.clone(), identifier)), - ) - .await; - match result { - Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), - Err(err) => { - logger::error!("Encryption error {:?}", err); - metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Encryption"); - Self::encrypt(masked_data, key, crypt_algo).await + #[async_trait] + impl< + V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, + S: masking::Strategy<serde_json::Value> + Send + Sync, + > TypeEncryption<serde_json::Value, V, S> + for crypto::Encryptable<Secret<serde_json::Value, S>> + { + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<serde_json::Value, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } } } } - } - #[instrument(skip_all)] - #[allow(unused_variables)] - async fn decrypt_via_api( - state: &KeyManagerState, - encrypted_data: Encryption, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::decrypt(encrypted_data, key, crypt_algo).await - } - #[cfg(feature = "encryption_service")] - { - let result: Result< - DecryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/decrypt", - TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), - ) - .await; - let decrypted = match result { - Ok(decrypted_data) => { - ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) - } - Err(err) => { - logger::error!("Decryption error {:?}", err); - Err(err.change_context(errors::CryptoError::EncodingFailed)) - } - }; - match decrypted { - Ok(de) => Ok(de), - Err(_) => { - metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Decryption"); - Self::decrypt(encrypted_data, key, crypt_algo).await + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::EncodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } } } } - } - - #[instrument(skip_all)] - async fn encrypt( - masked_data: Secret<serde_json::Value, S>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - let data = serde_json::to_vec(&masked_data.peek()) - .change_context(errors::CryptoError::DecodingFailed)?; - let encrypted_data = crypt_algo.encode_message(key, &data)?; - Ok(Self::new(masked_data, encrypted_data.into())) - } - #[instrument(skip_all)] - async fn decrypt( - encrypted_data: Encryption, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - let encrypted = encrypted_data.into_inner(); - let data = crypt_algo.decode_message(key, encrypted.clone())?; - - let value: serde_json::Value = - serde_json::from_slice(&data).change_context(errors::CryptoError::DecodingFailed)?; - Ok(Self::new(value.into(), encrypted)) - } + #[instrument(skip_all)] + async fn encrypt( + masked_data: Secret<serde_json::Value, S>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + let data = serde_json::to_vec(&masked_data.peek()) + .change_context(errors::CryptoError::DecodingFailed)?; + let encrypted_data = crypt_algo.encode_message(key, &data)?; + Ok(Self::new(masked_data, encrypted_data.into())) + } - #[allow(unused_variables)] - async fn batch_encrypt_via_api( - state: &KeyManagerState, - masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::batch_encrypt(masked_data, key, crypt_algo).await + #[instrument(skip_all)] + async fn decrypt( + encrypted_data: Encryption, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + let encrypted = encrypted_data.into_inner(); + let data = crypt_algo.decode_message(key, encrypted.clone())?; + + let value: serde_json::Value = serde_json::from_slice(&data) + .change_context(errors::CryptoError::DecodingFailed)?; + Ok(Self::new(value.into(), encrypted)) } - #[cfg(feature = "encryption_service")] - { - let result: Result< - BatchEncryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/encrypt", - BatchEncryptDataRequest::from((masked_data.clone(), identifier)), - ) - .await; - match result { - Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), - Err(err) => { - metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::error!("Encryption error {:?}", err); - logger::info!("Fall back to Application Encryption"); - Self::batch_encrypt(masked_data, key, crypt_algo).await + + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } } } } - } - #[allow(unused_variables)] - async fn batch_decrypt_via_api( - state: &KeyManagerState, - encrypted_data: FxHashMap<String, Encryption>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::batch_decrypt(encrypted_data, key, crypt_algo).await - } - #[cfg(feature = "encryption_service")] - { - let result: Result< - BatchDecryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/decrypt", - TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), - ) - .await; - let decrypted = match result { - Ok(decrypted_data) => { - ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) - } - Err(err) => { - logger::error!("Decryption error {:?}", err); - Err(err.change_context(errors::CryptoError::DecodingFailed)) - } - }; - match decrypted { - Ok(de) => Ok(de), - Err(_) => { - metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Decryption"); - Self::batch_decrypt(encrypted_data, key, crypt_algo).await + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } } } } - } - async fn batch_encrypt( - masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - masked_data - .into_iter() - .map(|(k, v)| { - let data = serde_json::to_vec(v.peek()) - .change_context(errors::CryptoError::DecodingFailed)?; - Ok(( - k, - Self::new(v, crypt_algo.encode_message(key, &data)?.into()), - )) - }) - .collect() - } + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + let data = serde_json::to_vec(v.peek()) + .change_context(errors::CryptoError::DecodingFailed)?; + Ok(( + k, + Self::new(v, crypt_algo.encode_message(key, &data)?.into()), + )) + }) + .collect() + } - async fn batch_decrypt( - encrypted_data: FxHashMap<String, Encryption>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - encrypted_data - .into_iter() - .map(|(k, v)| { - let data = crypt_algo.decode_message(key, v.clone().into_inner().clone())?; - - let value: serde_json::Value = serde_json::from_slice(&data) - .change_context(errors::CryptoError::DecodingFailed)?; - Ok((k, Self::new(value.into(), v.into_inner()))) - }) - .collect() + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + let data = crypt_algo.decode_message(key, v.clone().into_inner().clone())?; + + let value: serde_json::Value = serde_json::from_slice(&data) + .change_context(errors::CryptoError::DecodingFailed)?; + Ok((k, Self::new(value.into(), v.into_inner()))) + }) + .collect() + } } -} -#[async_trait] -impl< - V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<Vec<u8>> + Send + Sync, - > TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>> -{ - #[instrument(skip_all)] - #[allow(unused_variables)] - async fn encrypt_via_api( - state: &KeyManagerState, - masked_data: Secret<Vec<u8>, S>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::encrypt(masked_data, key, crypt_algo).await - } - #[cfg(feature = "encryption_service")] - { - let result: Result< - EncryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/encrypt", - EncryptDataRequest::from((masked_data.clone(), identifier)), - ) - .await; - match result { - Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), - Err(err) => { - logger::error!("Encryption error {:?}", err); - metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Encryption"); - Self::encrypt(masked_data, key, crypt_algo).await + #[async_trait] + impl< + V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, + S: masking::Strategy<Vec<u8>> + Send + Sync, + > TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>> + { + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<Vec<u8>, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } } } } - } - #[instrument(skip_all)] - #[allow(unused_variables)] - async fn decrypt_via_api( - state: &KeyManagerState, - encrypted_data: Encryption, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::decrypt(encrypted_data, key, crypt_algo).await - } - #[cfg(feature = "encryption_service")] - { - let result: Result< - DecryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/decrypt", - TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), - ) - .await; - let decrypted = match result { - Ok(decrypted_data) => { - ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) - } - Err(err) => { - logger::error!("Decryption error {:?}", err); - Err(err.change_context(errors::CryptoError::DecodingFailed)) - } - }; - match decrypted { - Ok(de) => Ok(de), - Err(_) => { - metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Decryption"); - Self::decrypt(encrypted_data, key, crypt_algo).await + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } } } } - } - #[instrument(skip_all)] - async fn encrypt( - masked_data: Secret<Vec<u8>, S>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?; - Ok(Self::new(masked_data, encrypted_data.into())) - } - - #[instrument(skip_all)] - async fn decrypt( - encrypted_data: Encryption, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<Self, errors::CryptoError> { - metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - let encrypted = encrypted_data.into_inner(); - let data = crypt_algo.decode_message(key, encrypted.clone())?; - Ok(Self::new(data.into(), encrypted)) - } + #[instrument(skip_all)] + async fn encrypt( + masked_data: Secret<Vec<u8>, S>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?; + Ok(Self::new(masked_data, encrypted_data.into())) + } - #[allow(unused_variables)] - async fn batch_encrypt_via_api( - state: &KeyManagerState, - masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::batch_encrypt(masked_data, key, crypt_algo).await + #[instrument(skip_all)] + async fn decrypt( + encrypted_data: Encryption, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + let encrypted = encrypted_data.into_inner(); + let data = crypt_algo.decode_message(key, encrypted.clone())?; + Ok(Self::new(data.into(), encrypted)) } - #[cfg(feature = "encryption_service")] - { - let result: Result< - BatchEncryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/encrypt", - BatchEncryptDataRequest::from((masked_data.clone(), identifier)), - ) - .await; - match result { - Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), - Err(err) => { - metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::error!("Encryption error {:?}", err); - logger::info!("Fall back to Application Encryption"); - Self::batch_encrypt(masked_data, key, crypt_algo).await + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } } } } - } - #[allow(unused_variables)] - async fn batch_decrypt_via_api( - state: &KeyManagerState, - encrypted_data: FxHashMap<String, Encryption>, - identifier: Identifier, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - #[cfg(not(feature = "encryption_service"))] - { - Self::batch_decrypt(encrypted_data, key, crypt_algo).await - } - #[cfg(feature = "encryption_service")] - { - let result: Result< - BatchDecryptDataResponse, - error_stack::Report<errors::KeyManagerClientError>, - > = call_encryption_service( - state, - Method::POST, - "data/decrypt", - TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), - ) - .await; - let decrypted = match result { - Ok(response) => { - ForeignTryFrom::foreign_try_from((encrypted_data.clone(), response)) - } - Err(err) => { - logger::error!("Decryption error {:?}", err); - Err(err.change_context(errors::CryptoError::DecodingFailed)) - } - }; - match decrypted { - Ok(de) => Ok(de), - Err(_) => { - metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::info!("Fall back to Application Decryption"); - Self::batch_decrypt(encrypted_data, key, crypt_algo).await + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(response) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), response)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } } } } - } - async fn batch_encrypt( - masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - masked_data - .into_iter() - .map(|(k, v)| { - Ok(( - k, - Self::new(v.clone(), crypt_algo.encode_message(key, v.peek())?.into()), - )) - }) - .collect() - } + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new(v.clone(), crypt_algo.encode_message(key, v.peek())?.into()), + )) + }) + .collect() + } - async fn batch_decrypt( - encrypted_data: FxHashMap<String, Encryption>, - key: &[u8], - crypt_algo: V, - ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { - metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); - encrypted_data - .into_iter() - .map(|(k, v)| { - Ok(( - k, - Self::new( - crypt_algo - .decode_message(key, v.clone().into_inner().clone())? - .into(), - v.into_inner(), - ), - )) - }) - .collect() + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new( + crypt_algo + .decode_message(key, v.clone().into_inner().clone())? + .into(), + v.into_inner(), + ), + )) + }) + .collect() + } } } - pub trait Lift<U> { type SelfWrapper<T>; type OtherWrapper<T, E>; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 5f3a820447d..78fc3760a47 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2754,8 +2754,9 @@ pub(crate) fn validate_connector_auth_type( pub async fn transfer_key_store_to_key_manager( state: SessionState, + req: admin_types::MerchantKeyTransferRequest, ) -> RouterResponse<admin_types::TransferKeyResponse> { - let resp = transfer_encryption_key(&state).await?; + let resp = transfer_encryption_key(&state, req).await?; Ok(service_api::ApplicationResponse::Json( admin_types::TransferKeyResponse { diff --git a/crates/router/src/core/encryption.rs b/crates/router/src/core/encryption.rs index efd7d3bfeaa..fb690b56cb2 100644 --- a/crates/router/src/core/encryption.rs +++ b/crates/router/src/core/encryption.rs @@ -1,3 +1,4 @@ +use api_models::admin::MerchantKeyTransferRequest; use base64::Engine; use common_utils::{ keymanager::transfer_key_to_key_manager, @@ -11,10 +12,16 @@ use crate::{consts::BASE64_ENGINE, errors, types::domain::UserKeyStore, SessionS pub async fn transfer_encryption_key( state: &SessionState, + req: MerchantKeyTransferRequest, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let db = &*state.store; let key_stores = db - .get_all_key_stores(&state.into(), &db.get_master_key().to_vec().into()) + .get_all_key_stores( + &state.into(), + &db.get_master_key().to_vec().into(), + req.from, + req.limit, + ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; send_request_to_key_service_for_merchant(state, key_stores).await @@ -24,17 +31,18 @@ pub async fn send_request_to_key_service_for_merchant( state: &SessionState, keys: Vec<MerchantKeyStore>, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { - futures::future::try_join_all(keys.into_iter().map(|key| async move { + let total = keys.len(); + for key in keys { let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); let req = EncryptionTransferRequest { identifier: Identifier::Merchant(key.merchant_id.clone()), key: key_encoded, }; - transfer_key_to_key_manager(&state.into(), req).await - })) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .map(|v| v.len()) + transfer_key_to_key_manager(&state.into(), req) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + } + Ok(total) } pub async fn send_request_to_key_service_for_user( diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index be33ccc69e1..e44493cff39 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1926,6 +1926,7 @@ pub async fn generate_recovery_codes( pub async fn transfer_user_key_store_keymanager( state: SessionState, + req: user_api::UserKeyTransferRequest, ) -> UserResponse<user_api::UserTransferKeyResponse> { let db = &state.global_store; @@ -1933,6 +1934,8 @@ pub async fn transfer_user_key_store_keymanager( .get_all_user_key_store( &(&state).into(), &state.store.get_master_key().to_vec().into(), + req.from, + req.limit, ) .await .change_context(UserErrors::InternalServerError)?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index ed2357c1a1c..7062ea141e0 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2193,8 +2193,12 @@ impl MerchantKeyStoreInterface for KafkaStore { &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, + from: u32, + to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { - self.diesel_store.get_all_key_stores(state, key).await + self.diesel_store + .get_all_key_stores(state, key, from, to) + .await } } @@ -3067,8 +3071,12 @@ impl UserKeyStoreInterface for KafkaStore { &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, + from: u32, + limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { - self.diesel_store.get_all_user_key_store(state, key).await + self.diesel_store + .get_all_user_key_store(state, key, from, limit) + .await } } diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 1cc12796bc6..21c1a184425 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -49,6 +49,8 @@ pub trait MerchantKeyStoreInterface { &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, + from: u32, + to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; } @@ -183,15 +185,17 @@ impl MerchantKeyStoreInterface for Store { &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, + from: u32, + to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - let fetch_func = || async { - diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores(&conn) - .await - .map_err(|err| report!(errors::StorageError::from(err))) - }; + let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores( + &conn, from, to, + ) + .await + .map_err(|err| report!(errors::StorageError::from(err)))?; - futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + futures::future::try_join_all(stores.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert(state, key, merchant_id) @@ -295,6 +299,8 @@ impl MerchantKeyStoreInterface for MockDb { &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, + _from: u32, + _to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs index e7dbe531c65..111989a293e 100644 --- a/crates/router/src/db/user_key_store.rs +++ b/crates/router/src/db/user_key_store.rs @@ -34,6 +34,8 @@ pub trait UserKeyStoreInterface { &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, + from: u32, + limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>; } @@ -81,16 +83,17 @@ impl UserKeyStoreInterface for Store { &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, + from: u32, + limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - let fetch_func = || async { - diesel_models::user_key_store::UserKeyStore::get_all_user_key_stores(&conn) - .await - .map_err(|err| report!(errors::StorageError::from(err))) - }; - - futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + let key_stores = diesel_models::user_key_store::UserKeyStore::get_all_user_key_stores( + &conn, from, limit, + ) + .await + .map_err(|err| report!(errors::StorageError::from(err)))?; + futures::future::try_join_all(key_stores.into_iter().map(|key_store| async { let user_id = key_store.user_id.clone(); key_store .convert(state, key, user_id) @@ -137,6 +140,8 @@ impl UserKeyStoreInterface for MockDb { &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, + _from: u32, + _limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let user_key_store = self.user_key_store.lock().await; diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs index 7bf66dd0951..9eb8f1021aa 100644 --- a/crates/router/src/events/api_logs.rs +++ b/crates/router/src/events/api_logs.rs @@ -1,6 +1,6 @@ use actix_web::HttpRequest; pub use common_utils::events::{ApiEventMetric, ApiEventsType}; -use common_utils::impl_misc_api_event_type; +use common_utils::impl_api_event_type; use router_env::{tracing_actix_web::RequestId, types::FlowMetric}; use serde::Serialize; use time::OffsetDateTime; @@ -98,24 +98,30 @@ impl KafkaMessage for ApiEvent { } } -impl_misc_api_event_type!( - Config, - CreateFileRequest, - FileId, - AttachEvidenceRequest, - ConfigUpdate +impl_api_event_type!( + Miscellaneous, + ( + Config, + CreateFileRequest, + FileId, + AttachEvidenceRequest, + ConfigUpdate + ) ); #[cfg(feature = "dummy_connector")] -impl_misc_api_event_type!( - DummyConnectorPaymentCompleteRequest, - DummyConnectorPaymentRequest, - DummyConnectorPaymentResponse, - DummyConnectorPaymentRetrieveRequest, - DummyConnectorPaymentConfirmRequest, - DummyConnectorRefundRetrieveRequest, - DummyConnectorRefundResponse, - DummyConnectorRefundRequest +impl_api_event_type!( + Miscellaneous, + ( + DummyConnectorPaymentCompleteRequest, + DummyConnectorPaymentRequest, + DummyConnectorPaymentResponse, + DummyConnectorPaymentRetrieveRequest, + DummyConnectorPaymentConfirmRequest, + DummyConnectorRefundRetrieveRequest, + DummyConnectorRefundResponse, + DummyConnectorRefundRequest + ) ); impl ApiEventMetric for PaymentsRedirectResponseData { diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 74bb775d9c0..fe791bfaea9 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -658,14 +658,15 @@ pub async fn merchant_account_kv_status( pub async fn merchant_account_transfer_keys( state: web::Data<AppState>, req: HttpRequest, + payload: web::Json<api_models::admin::MerchantKeyTransferRequest>, ) -> HttpResponse { let flow = Flow::ConfigKeyFetch; api::server_wrap( flow, state, &req, - (), - |state, _, _, _| transfer_key_store_to_key_manager(state), + payload.into_inner(), + |state, _, req, _| transfer_key_store_to_key_manager(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 29935bc8ab7..39839e423ea 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -896,15 +896,19 @@ pub async fn terminate_auth_select( .await } -pub async fn transfer_user_key(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { +pub async fn transfer_user_key( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<user_api::UserKeyTransferRequest>, +) -> HttpResponse { let flow = Flow::UserTransferKey; Box::pin(api::server_wrap( flow, state.clone(), &req, - (), - |state, _, _, _| user_core::transfer_user_key_store_keymanager(state), + payload.into_inner(), + |state, _, req, _| user_core::transfer_user_key_store_keymanager(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ))
2024-07-18T08:01:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> Add offset and limit to key transfer API ## 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 adds `from` and `limit` parameters to Key transfer API and thus providing a way to transfer the keys in batches. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Run `/accounts/transfer` with `from` and `limit` parameters. It should respond with the `total_transferred` same as `limit`. ```bash curl --location 'http://localhost:8080/accounts/transfer' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "from": 0, "limit": 2 }' ``` 2. Do the same thing for `user/key/transfer` ```bash curl --location 'http://localhost:8080/user/key/transfer' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "from": 0, "limit": 2 }' ```` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
06f1406cbc350a71f961a19dc2a6cfef2ceeb3a1
juspay/hyperswitch
juspay__hyperswitch-5355
Bug: Remove the locker call in the psync flow There is a locker call that is happening the psync flow. This pr is to remove that call as it is not required.
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index f5bc4014655..be54ead0ac1 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -299,27 +299,18 @@ where #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, - state: &'a SessionState, - payment_data: &mut PaymentData<F>, - storage_scheme: enums::MerchantStorageScheme, - merchant_key_store: &domain::MerchantKeyStore, - customer: &Option<domain::Customer>, - business_profile: Option<&diesel_models::business_profile::BusinessProfile>, + _state: &'a SessionState, + _payment_data: &mut PaymentData<F>, + _storage_scheme: enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: Option<&diesel_models::business_profile::BusinessProfile>, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, Option<api::PaymentMethodData>, Option<String>, )> { - helpers::make_pm_data( - Box::new(self), - state, - payment_data, - merchant_key_store, - customer, - storage_scheme, - business_profile, - ) - .await + Ok((Box::new(self), None, None)) } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 5d4a5037b70..5f20ccdf277 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -85,27 +85,18 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, - state: &'a SessionState, - payment_data: &mut PaymentData<F>, - storage_scheme: enums::MerchantStorageScheme, - merchant_key_store: &domain::MerchantKeyStore, - customer: &Option<domain::Customer>, - business_profile: Option<&diesel_models::business_profile::BusinessProfile>, + _state: &'a SessionState, + _payment_data: &mut PaymentData<F>, + _storage_scheme: enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: Option<&diesel_models::business_profile::BusinessProfile>, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, Option<api::PaymentMethodData>, Option<String>, )> { - helpers::make_pm_data( - Box::new(self), - state, - payment_data, - merchant_key_store, - customer, - storage_scheme, - business_profile, - ) - .await + Ok((Box::new(self), None, None)) } #[instrument(skip_all)]
2024-07-17T09:52:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> There is a locker call that is happening the psync flow. This pr is to remove that call as it is not required. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant connector account -> Make payment with setup future usage as on_session ``` { "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_{{$timestamp}}", "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": "off_session", "return_url": "http://127.0.0.1:4040", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "838" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "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": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` ``` { "payment_id": "pay_L09mAA2vJWMpikulL0B1", "merchant_id": "merchant_1721237060", "status": "succeeded", "amount": 100, "net_amount": 100, "amount_capturable": 0, "amount_received": 100, "connector": "cybersource", "client_secret": "pay_L09mAA2vJWMpikulL0B1_secret_qhp7eDeERyGyd7ERAjI5", "created": "2024-07-17T17:39:40.909Z", "currency": "USD", "customer_id": "cu_1721237981", "customer": { "id": "cu_1721237981", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_GoLxIHws4sqqymi4NwkY", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1721237981", "created_at": 1721237980, "expires": 1721241580, "secret": "epk_5d472cb008504e1ea6855ce02453891e" }, "manual_retry_allowed": false, "connector_transaction_id": "7212379820306293103955", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_L09mAA2vJWMpikulL0B1_1", "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bKNbIwdnASzrehxu8SEv", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T17:54:40.909Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_m9VS7XdixuPx8HFIIX0z", "payment_method_status": null, "updated": "2024-07-17T17:39:42.896Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> Retrieve the above payment with the payment_id ``` curl --location 'http://localhost:8080/payments/pay_L09mAA2vJWMpikulL0B1' \ --header 'Accept: application/json' \ --header 'api-key:' ``` ``` { "payment_id": "pay_L09mAA2vJWMpikulL0B1", "merchant_id": "merchant_1721237060", "status": "succeeded", "amount": 100, "net_amount": 100, "amount_capturable": 0, "amount_received": 100, "connector": "cybersource", "client_secret": "pay_L09mAA2vJWMpikulL0B1_secret_qhp7eDeERyGyd7ERAjI5", "created": "2024-07-17T17:39:40.909Z", "currency": "USD", "customer_id": "cu_1721237981", "customer": { "id": "cu_1721237981", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_GoLxIHws4sqqymi4NwkY", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7212379820306293103955", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_L09mAA2vJWMpikulL0B1_1", "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bKNbIwdnASzrehxu8SEv", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T17:54:40.909Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_m9VS7XdixuPx8HFIIX0z", "payment_method_status": "active", "updated": "2024-07-17T17:39:42.896Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> The below is the response of payments retrieve without this pr changes. (With the locker call being present in the psync flow). And there is no difference between above retrieve response and this. ``` { "payment_id": "pay_L09mAA2vJWMpikulL0B1", "merchant_id": "merchant_1721237060", "status": "succeeded", "amount": 100, "net_amount": 100, "amount_capturable": 0, "amount_received": 100, "connector": "cybersource", "client_secret": "pay_L09mAA2vJWMpikulL0B1_secret_qhp7eDeERyGyd7ERAjI5", "created": "2024-07-17T17:39:40.909Z", "currency": "USD", "customer_id": "cu_1721237981", "customer": { "id": "cu_1721237981", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_GoLxIHws4sqqymi4NwkY", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7212379820306293103955", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_L09mAA2vJWMpikulL0B1_1", "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bKNbIwdnASzrehxu8SEv", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T17:54:40.909Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_m9VS7XdixuPx8HFIIX0z", "payment_method_status": "active", "updated": "2024-07-17T17:39:42.896Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> Create a payment with confirm false for the above customer ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1721237981" }' ``` ``` { "payment_id": "pay_dfkaTLO2JS0sp9O5b2cz", "merchant_id": "merchant_1721237060", "status": "requires_payment_method", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_dfkaTLO2JS0sp9O5b2cz_secret_r5hc7GhSo8ppJTSNM0XJ", "created": "2024-07-17T17:43:11.348Z", "currency": "USD", "customer_id": "cu_1721237981", "customer": { "id": "cu_1721237981", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "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": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1721237981", "created_at": 1721238191, "expires": 1721241791, "secret": "epk_cbb1db0f397e48fc90584284e494b7af" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T17:58:11.348Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-17T17:43:11.359Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> List payment method for the customer with the client secret ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_dfkaTLO2JS0sp9O5b2cz_secret_r5hc7GhSo8ppJTSNM0XJ' \ --header 'Accept: application/json' \ --header 'api-key:' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_hn7MoWvP3D9HB5hirMyf", "payment_method_id": "pm_m9VS7XdixuPx8HFIIX0z", "customer_id": "cu_1721237981", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": "STRIPE PAYMENTS UK LIMITED", "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": "Visa", "issuer_country": "UNITEDKINGDOM", "last4_digits": "4242", "expiry_month": "03", "expiry_year": "2030", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": "Visa", "card_isin": "424242", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_type": "CREDIT", "saved_to_locker": true }, "metadata": null, "created": "2024-07-17T17:39:42.886Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-07-17T17:39:42.886Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null } } ], "is_guest_customer": false } ``` -> Confirm the payment with the above token ``` curl --location 'http://localhost:8080/payments/pay_dfkaTLO2JS0sp9O5b2cz/confirm' \ --header 'api-key: pk_dev_582a9b99149a4c12a441287a7356aacc' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_hn7MoWvP3D9HB5hirMyf", "client_secret": "pay_dfkaTLO2JS0sp9O5b2cz_secret_r5hc7GhSo8ppJTSNM0XJ", "payment_method": "card", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } } }' ``` ``` { "payment_id": "pay_dfkaTLO2JS0sp9O5b2cz", "merchant_id": "merchant_1721237060", "status": "succeeded", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": 10000, "connector": "cybersource", "client_secret": "pay_dfkaTLO2JS0sp9O5b2cz_secret_r5hc7GhSo8ppJTSNM0XJ", "created": "2024-07-17T17:43:11.348Z", "currency": "USD", "customer_id": "cu_1721237981", "customer": { "id": "cu_1721237981", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "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": null, "payment_method_data": null, "payment_token": "token_hn7MoWvP3D9HB5hirMyf", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7212382850096434103954", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_dfkaTLO2JS0sp9O5b2cz_1", "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bKNbIwdnASzrehxu8SEv", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T17:58:11.348Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_m9VS7XdixuPx8HFIIX0z", "payment_method_status": "active", "updated": "2024-07-17T17:44:45.545Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> Retrieve the payment done with the token ``` { "payment_id": "pay_dfkaTLO2JS0sp9O5b2cz", "merchant_id": "merchant_1721237060", "status": "succeeded", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": 10000, "connector": "cybersource", "client_secret": "pay_dfkaTLO2JS0sp9O5b2cz_secret_r5hc7GhSo8ppJTSNM0XJ", "created": "2024-07-17T17:43:11.348Z", "currency": "USD", "customer_id": "cu_1721237981", "customer": { "id": "cu_1721237981", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "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": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_hn7MoWvP3D9HB5hirMyf", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7212382850096434103954", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_dfkaTLO2JS0sp9O5b2cz_1", "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bKNbIwdnASzrehxu8SEv", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T17:58:11.348Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_m9VS7XdixuPx8HFIIX0z", "payment_method_status": "active", "updated": "2024-07-17T17:44:45.545Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> Migrate the masked card with connector mandate details ``` curl --location 'http://localhost:8080/payment_methods/migrate' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "payment_method": "card", "merchant_id": "merchant_1721237060", "card": { "card_number": "424242xxxxxx4242", "card_exp_month": "10", "card_exp_year": "33", "nick_name": "Joh" }, "customer_id": "cu_1721238369", "connector_mandate_details": { "mca_bKNbIwdnASzrehxu8SEv": { "connector_mandate_id": "********", "original_payment_authorized_amount": 6560, "original_payment_authorized_currency": "USD" } } } ' ``` ``` { "merchant_id": "merchant_1721237060", "customer_id": "cu_1721238369", "payment_method_id": "pm_MkCwer0JR8PXILV5s4Vb", "payment_method": "card", "payment_method_type": null, "card": { "scheme": "Visa", "issuer_country": "UNITEDKINGDOM", "last4_digits": "4242", "expiry_month": "10", "expiry_year": "33", "card_token": null, "card_holder_name": null, "card_fingerprint": null, "nick_name": "Joh", "card_network": "Visa", "card_isin": "424242", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_type": "CREDIT", "saved_to_locker": false }, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": null, "metadata": null, "created": "2024-07-17T17:46:20.079Z", "last_used_at": null, "client_secret": null } ``` -> Create a payment with confirm false with the above customer id ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_7hNNsvTXdOymvARJTKp0VNc2osmqO5FSwBd6ApgqPF9je9OkvSWsLcQvjtyfJnxy' \ --header 'Content-Type: application/json' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "setup_future_usage": "off_session", "customer_id": "cu_1721238369" }' ``` ``` { "payment_id": "pay_9LYl8otoXv4cPNrAYXWh", "merchant_id": "merchant_1721237060", "status": "requires_payment_method", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_9LYl8otoXv4cPNrAYXWh_secret_gsjw6b8LtQ6RrkE0znvT", "created": "2024-07-17T17:47:12.188Z", "currency": "USD", "customer_id": "cu_1721238369", "customer": { "id": "cu_1721238369", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1721238369", "created_at": 1721238432, "expires": 1721242032, "secret": "epk_df357eedb02c464ebdb7be4d486d7a74" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T18:02:12.188Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-17T17:47:12.200Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> List payment method ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_9LYl8otoXv4cPNrAYXWh_secret_gsjw6b8LtQ6RrkE0znvT' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_582a9b99149a4c12a441287a7356aacc' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_cBHc67J4zss1pxWFdFT0", "payment_method_id": "pm_MkCwer0JR8PXILV5s4Vb", "customer_id": "cu_1721238369", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": "Visa", "issuer_country": "UNITEDKINGDOM", "last4_digits": "4242", "expiry_month": "10", "expiry_year": "33", "card_token": null, "card_holder_name": null, "card_fingerprint": null, "nick_name": "Joh", "card_network": "Visa", "card_isin": "424242", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_type": "CREDIT", "saved_to_locker": false }, "metadata": null, "created": "2024-07-17T17:46:20.079Z", "bank": null, "surcharge_details": null, "requires_cvv": false, "last_used_at": "2024-07-17T17:46:20.079Z", "default_payment_method_set": true, "billing": null } ], "is_guest_customer": false } ``` -> Confirm the payment with the token ``` curl --location 'http://localhost:8080/payments/pay_9LYl8otoXv4cPNrAYXWh/confirm' \ --header 'api-key: pk_dev_582a9b99149a4c12a441287a7356aacc' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_cBHc67J4zss1pxWFdFT0", "client_secret": "pay_9LYl8otoXv4cPNrAYXWh_secret_gsjw6b8LtQ6RrkE0znvT", "payment_method": "card", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } } }' ``` ``` { "payment_id": "pay_9LYl8otoXv4cPNrAYXWh", "merchant_id": "merchant_1721237060", "status": "succeeded", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": 10000, "connector": "cybersource", "client_secret": "pay_9LYl8otoXv4cPNrAYXWh_secret_gsjw6b8LtQ6RrkE0znvT", "created": "2024-07-17T17:47:12.188Z", "currency": "USD", "customer_id": "cu_1721238369", "customer": { "id": "cu_1721238369", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": "token_cBHc67J4zss1pxWFdFT0", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7212385852016467503954", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_9LYl8otoXv4cPNrAYXWh_1", "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bKNbIwdnASzrehxu8SEv", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T18:02:12.188Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_MkCwer0JR8PXILV5s4Vb", "payment_method_status": "active", "updated": "2024-07-17T17:49:46.020Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> Retrieve the payment ``` { "payment_id": "pay_9LYl8otoXv4cPNrAYXWh", "merchant_id": "merchant_1721237060", "status": "succeeded", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": 10000, "connector": "cybersource", "client_secret": "pay_9LYl8otoXv4cPNrAYXWh_secret_gsjw6b8LtQ6RrkE0znvT", "created": "2024-07-17T17:47:12.188Z", "currency": "USD", "customer_id": "cu_1721238369", "customer": { "id": "cu_1721238369", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "33", "card_holder_name": null, "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_cBHc67J4zss1pxWFdFT0", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7212385852016467503954", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_9LYl8otoXv4cPNrAYXWh_1", "payment_link": null, "profile_id": "pro_o1oNJ5hTuZwe7y5fyNIM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bKNbIwdnASzrehxu8SEv", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-17T18:02:12.188Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_MkCwer0JR8PXILV5s4Vb", "payment_method_status": "active", "updated": "2024-07-17T17:49:46.020Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ecc862c3543be37e2cc7959f450ca51770978ae5
juspay/hyperswitch
juspay__hyperswitch-5354
Bug: Add support for passing the domain dynamically in the session call Now the merchant domain is being collected while enabling apple pay for a particular merchant connector account. Instead this pr is to add support to accept the merchant domain dynamically in the session call. As this is a test feature we have a fallback in which if the session call fails with the dynamic domain then it will be retried with the domain configured for the mca.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index c04af204493..619f345a333 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -745,6 +745,7 @@ pub struct HeaderPayload { pub x_hs_latency: Option<bool>, pub browser_name: Option<api_enums::BrowserName>, pub x_client_platform: Option<api_enums::ClientPlatform>, + pub x_merchant_domain: Option<String>, } impl HeaderPayload { diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 883203ad99e..4441e349d9f 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -210,6 +210,7 @@ async fn create_applepay_session_token( apple_pay_merchant_cert_key, apple_pay_merchant_identifier, merchant_business_country, + merchant_configured_domain_optional, ) = match apple_pay_metadata { payment_types::ApplepaySessionTokenMetadata::ApplePayCombined( apple_pay_combined_metadata, @@ -232,7 +233,7 @@ async fn create_applepay_session_token( let apple_pay_session_request = get_session_request_for_simplified_apple_pay( merchant_identifier.clone(), - session_token_data, + session_token_data.clone(), ); let apple_pay_merchant_cert = state @@ -256,6 +257,7 @@ async fn create_applepay_session_token( apple_pay_merchant_cert_key, merchant_identifier, merchant_business_country, + Some(session_token_data.initiative_context), ) } payment_types::ApplePayCombinedMetadata::Manual { @@ -264,8 +266,10 @@ async fn create_applepay_session_token( } => { logger::info!("Apple pay manual flow"); - let apple_pay_session_request = - get_session_request_for_manual_apple_pay(session_token_data.clone()); + let apple_pay_session_request = get_session_request_for_manual_apple_pay( + session_token_data.clone(), + header_payload.x_merchant_domain.clone(), + ); let merchant_business_country = session_token_data.merchant_business_country; @@ -276,6 +280,7 @@ async fn create_applepay_session_token( session_token_data.certificate_keys, session_token_data.merchant_identifier, merchant_business_country, + session_token_data.initiative_context, ) } }, @@ -284,6 +289,7 @@ async fn create_applepay_session_token( let apple_pay_session_request = get_session_request_for_manual_apple_pay( apple_pay_metadata.session_token_data.clone(), + header_payload.x_merchant_domain.clone(), ); let merchant_business_country = apple_pay_metadata @@ -299,6 +305,7 @@ async fn create_applepay_session_token( .clone(), apple_pay_metadata.session_token_data.merchant_identifier, merchant_business_country, + apple_pay_metadata.session_token_data.initiative_context, ) } }; @@ -383,9 +390,9 @@ async fn create_applepay_session_token( .attach_printable("Failed to obtain apple pay session request")?; let applepay_session_request = build_apple_pay_session_request( state, - apple_pay_session_request, - apple_pay_merchant_cert, - apple_pay_merchant_cert_key, + apple_pay_session_request.clone(), + apple_pay_merchant_cert.clone(), + apple_pay_merchant_cert_key.clone(), )?; let response = services::call_connector_api( @@ -395,10 +402,43 @@ async fn create_applepay_session_token( ) .await; - // logging the error if present in session call response - log_session_response_if_error(&response); + let updated_response = match ( + response.as_ref().ok(), + header_payload.x_merchant_domain.clone(), + ) { + (Some(Err(error)), Some(_)) => { + logger::error!( + "Retry apple pay session call with the merchant configured domain {error:?}" + ); + let merchant_configured_domain = merchant_configured_domain_optional + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to get initiative_context for apple pay session call retry", + )?; + let apple_pay_retry_session_request = + payment_types::ApplepaySessionRequest { + initiative_context: merchant_configured_domain, + ..apple_pay_session_request + }; + let applepay_retry_session_request = build_apple_pay_session_request( + state, + apple_pay_retry_session_request, + apple_pay_merchant_cert, + apple_pay_merchant_cert_key, + )?; + services::call_connector_api( + state, + applepay_retry_session_request, + "create_apple_pay_session_token", + ) + .await + } + _ => response, + }; - response + // logging the error if present in session call response + log_session_response_if_error(&updated_response); + updated_response .ok() .and_then(|apple_pay_res| { apple_pay_res @@ -454,6 +494,7 @@ fn get_session_request_for_simplified_apple_pay( fn get_session_request_for_manual_apple_pay( session_token_data: payment_types::SessionTokenInfo, + merchant_domain: Option<String>, ) -> RouterResult<payment_types::ApplepaySessionRequest> { let initiative_context = session_token_data .initiative_context @@ -463,7 +504,7 @@ fn get_session_request_for_manual_apple_pay( merchant_identifier: session_token_data.merchant_identifier.clone(), display_name: session_token_data.display_name.clone(), initiative: session_token_data.initiative.to_string(), - initiative_context, + initiative_context: merchant_domain.unwrap_or(initiative_context), }) } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 69a76be5bc0..38000f7b664 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -79,6 +79,7 @@ pub mod headers { pub const CONTENT_LENGTH: &str = "Content-Length"; pub const BROWSER_NAME: &str = "x-browser-name"; pub const X_CLIENT_PLATFORM: &str = "x-client-platform"; + pub const X_MERCHANT_DOMAIN: &str = "x-merchant-domain"; } pub mod pii { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 9a42916f68d..d32f62ed0be 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -21,7 +21,7 @@ use super::domain; use crate::{ core::errors, headers::{ - BROWSER_NAME, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, + BROWSER_NAME, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, }, services::authentication::get_header_value_by_key, @@ -1157,6 +1157,9 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { .unwrap_or(api_enums::ClientPlatform::Unknown) }); + let x_merchant_domain = + get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string()); + Ok(Self { payment_confirm_source, client_source, @@ -1164,6 +1167,7 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { x_hs_latency: Some(x_hs_latency), browser_name, x_client_platform, + x_merchant_domain, }) } }
2024-07-17T09:41:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Now the merchant domain is being collected while enabling apple pay for a particular merchant connector account. Instead this pr is to add support to accept the merchant domain dynamically in the session call. As this is a test feature we have a fallback in which if the session call fails with the dynamic domain then it will be retried with the domain configured for the mca. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant connector account with apple pay enabled -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_b7ym5n82JbU8NDduwRHW8QlBYHMR6rXEOCa7m6vEmPImmKbAvZWbfDkVffKIGkv3' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "test_1" }' ``` -> Make a session call with the domain passed in header ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key:' \ --data '{ "payment_id": "pay_W9jZdVDlhrpkZdl56Woq", "wallets": [], "client_secret": "pay_W9jZdVDlhrpkZdl56Woq_secret_Jf9bWFRNA1ebDcWz2IwN" }' ``` <img width="1127" alt="image" src="https://github.com/user-attachments/assets/6cb3d4ee-e9b6-40b6-bf0a-e59238cecb37"> -> Provide a wrong domain in the header. The session call will still get succeeded with retry ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-merchant-domain: hyperswitch-demo-store.netlify.app' \ --header 'api-key: pk_dev_97c8390e78a54e178d30b1f28bf87743' \ --data '{ "payment_id": "pay_VNOvTIkIdl4pA2OWCCjV", "wallets": [], "client_secret": "pay_VNOvTIkIdl4pA2OWCCjV_secret_WeQ8F31Mjvddn91oYZuG" }' ``` <img width="1158" alt="image" src="https://github.com/user-attachments/assets/fe0d7067-dd5c-4525-82f5-3f0d31c20476"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2d204c9f7348c4ed121ab472ef1b5bb8d9d32d24
juspay/hyperswitch
juspay__hyperswitch-5372
Bug: [FEATURE] provision for secure payment links ### Feature Description Provide open and secure payment links for different use cases - Open links - Accessible by anyone - Can be opened in new tabs - Can be iframed by any host - SPMs are never listed - Secure links - Can be opened only in iframes by allowed_domains (configurable) - SPMs can be listed (configurable) ### Possible Implementation When payment links creation is requested, create two links - Open - Always create this link - Secure - Create only if allowed_domains are set in the profile - If created, store these domains in DB When payment links render is requested - Open - open as is (status vs initiate) - Secure - Validate if the request is coming from an iframe - Validate Origin + Referer headers - Client side script to not load the SDK incase iframe is loaded in top ### 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 66b38d09c1f..cf5864e96e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2014,6 +2014,7 @@ dependencies = [ "error-stack", "fake", "futures 0.3.30", + "globset", "hex", "http 0.2.12", "masking", @@ -6063,7 +6064,6 @@ dependencies = [ "events", "external_services", "futures 0.3.30", - "globset", "hex", "http 0.2.12", "hyper 0.14.28", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 4f1143efaa8..0ddca226f5b 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1729,7 +1729,7 @@ impl BusinessGenericLinkConfig { .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { - return Err("Invalid host domain name received"); + return Err("Invalid host domain name received in payout_link_config"); } let are_allowed_domains_valid = self @@ -1738,7 +1738,7 @@ impl BusinessGenericLinkConfig { .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)); if !are_allowed_domains_valid { - return Err("Invalid allowed domain names received"); + return Err("Invalid allowed domain names received in payout_link_config"); } Ok(()) @@ -1755,6 +1755,37 @@ pub struct BusinessPaymentLinkConfig { pub default_config: Option<PaymentLinkConfigRequest>, /// list of configs for multi theme setup pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>, + /// A list of allowed domains (glob patterns) where this link can be embedded / opened from + #[schema(value_type = Option<HashSet<String>>)] + pub allowed_domains: Option<HashSet<String>>, +} + +impl BusinessPaymentLinkConfig { + pub fn validate(&self) -> Result<(), &str> { + let host_domain_valid = self + .domain_name + .clone() + .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) + .unwrap_or(true); + if !host_domain_valid { + return Err("Invalid host domain name received in payment_link_config"); + } + + let are_allowed_domains_valid = self + .allowed_domains + .clone() + .map(|allowed_domains| { + allowed_domains + .iter() + .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)) + }) + .unwrap_or(true); + if !are_allowed_domains_valid { + return Err("Invalid allowed domain names received in payment_link_config"); + } + + Ok(()) + } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] @@ -1793,6 +1824,8 @@ pub struct PaymentLinkConfig { pub display_sdk_only: bool, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: bool, + /// A list of allowed domains (glob patterns) where this link can be embedded / opened from + pub allowed_domains: Option<HashSet<String>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a466288b416..cc29d5330ce 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5300,7 +5300,11 @@ pub struct RetrievePaymentLinkRequest { #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { + /// URL for rendering the open payment link pub link: String, + /// URL for rendering the secure payment link + pub secure_link: Option<String>, + /// Identifier for the payment link pub payment_link_id: String, } @@ -5311,7 +5315,7 @@ pub struct RetrievePaymentLinkResponse { /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, - /// Payment Link + /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] @@ -5328,6 +5332,8 @@ pub struct RetrievePaymentLinkResponse { pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, + /// Secure payment link (with security checks and listing saved payment methods) + pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] @@ -5339,8 +5345,8 @@ pub struct PaymentLinkInitiateRequest { #[derive(Debug, serde::Serialize)] #[serde(untagged)] -pub enum PaymentLinkData<'a> { - PaymentLinkDetails(&'a PaymentLinkDetails), +pub enum PaymentLinkData { + PaymentLinkDetails(PaymentLinkDetails), PaymentLinkStatusDetails(PaymentLinkStatusDetails), } @@ -5362,7 +5368,13 @@ pub struct PaymentLinkDetails { pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, +} + +#[derive(Debug, serde::Serialize, Clone)] +pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, + #[serde(flatten)] + pub payment_link_details: PaymentLinkDetails, } #[derive(Debug, serde::Serialize)] diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 4939c0f1609..40b9c105626 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -25,6 +25,7 @@ bytes = "1.6.0" diesel = "2.1.5" error-stack = "0.4.1" futures = { version = "0.3.30", optional = true } +globset = "0.4.14" hex = "0.4.3" http = "0.2.12" md5 = "0.7.0" diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index e52d24c9baa..75ba14586b1 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -1,5 +1,7 @@ //! Commonly used constants +use std::collections::HashSet; + /// Number of characters in a generated ID pub const ID_LENGTH: usize = 20; @@ -81,6 +83,9 @@ pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false; /// Default bool to enable saved payment method pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false; +/// Default allowed domains for payment links +pub const DEFAULT_ALLOWED_DOMAINS: Option<HashSet<String>> = None; + /// Default ttl for Extended card info in redis (in seconds) pub const DEFAULT_TTL_FOR_EXTENDED_CARD_INFO: u16 = 15 * 60; diff --git a/crates/common_utils/src/validation.rs b/crates/common_utils/src/validation.rs index 1362f3b5f74..9403e6720a9 100644 --- a/crates/common_utils/src/validation.rs +++ b/crates/common_utils/src/validation.rs @@ -1,6 +1,9 @@ //! Custom validations for some shared types. +use std::collections::HashSet; + use error_stack::report; +use globset::Glob; use once_cell::sync::Lazy; use regex::Regex; #[cfg(feature = "logs")] @@ -57,6 +60,27 @@ pub fn validate_email(email: &str) -> CustomResult<(), ValidationError> { Ok(()) } +/// Checks whether a given domain matches against a list of valid domain glob patterns +pub fn validate_domain_against_allowed_domains( + domain: &str, + allowed_domains: HashSet<String>, +) -> bool { + allowed_domains.iter().any(|allowed_domain| { + Glob::new(allowed_domain) + .map(|glob| glob.compile_matcher().is_match(domain)) + .map_err(|err| { + let err_msg = format!( + "Invalid glob pattern for configured allowed_domain [{:?}]! - {:?}", + allowed_domain, err + ); + #[cfg(feature = "logs")] + logger::error!(err_msg); + err_msg + }) + .unwrap_or(false) + }) +} + #[cfg(test)] mod tests { use fake::{faker::internet::en::SafeEmail, Fake}; diff --git a/crates/diesel_models/src/payment_link.rs b/crates/diesel_models/src/payment_link.rs index d5887143019..347a730eb68 100644 --- a/crates/diesel_models/src/payment_link.rs +++ b/crates/diesel_models/src/payment_link.rs @@ -24,6 +24,7 @@ pub struct PaymentLink { pub payment_link_config: Option<serde_json::Value>, pub description: Option<String>, pub profile_id: Option<String>, + pub secure_link: Option<String>, } #[derive( @@ -54,4 +55,5 @@ pub struct PaymentLinkNew { pub payment_link_config: Option<serde_json::Value>, pub description: Option<String>, pub profile_id: Option<String>, + pub secure_link: Option<String>, } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 544a99bccb5..526a19ed5bf 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -922,6 +922,8 @@ diesel::table! { description -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, + #[max_length = 255] + secure_link -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index e60e2da0a47..bac1ca82262 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -928,6 +928,8 @@ diesel::table! { description -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, + #[max_length = 255] + secure_link -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs index 39f3f04c548..d62516234ea 100644 --- a/crates/hyperswitch_domain_models/src/api.rs +++ b/crates/hyperswitch_domain_models/src/api.rs @@ -71,6 +71,7 @@ pub enum GenericLinksData { PayoutLink(GenericLinkFormData), PayoutLinkStatus(GenericLinkStatusData), PaymentMethodCollectStatus(GenericLinkStatusData), + SecurePaymentLink(PaymentLinkFormData), } impl Display for GenericLinksData { @@ -84,6 +85,7 @@ impl Display for GenericLinksData { Self::PayoutLink(_) => "PayoutLink", Self::PayoutLinkStatus(_) => "PayoutLinkStatus", Self::PaymentMethodCollectStatus(_) => "PaymentMethodCollectStatus", + Self::SecurePaymentLink(_) => "SecurePaymentLink", } ) } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e7a0db07e8e..30cc7287b5a 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -61,7 +61,6 @@ dyn-clone = "1.0.17" encoding_rs = "0.8.33" error-stack = "0.4.1" futures = "0.3.30" -globset = "0.4.14" hex = "0.4.3" http = "0.2.12" hyper = "0.14.28" diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 51fffea3b53..fc34ec2f7db 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3139,12 +3139,15 @@ pub async fn update_business_profile( let payment_link_config = request .payment_link_config .as_ref() - .map(|pl_metadata| { - pl_metadata.encode_to_value().change_context( + .map(|payment_link_conf| match payment_link_conf.validate() { + Ok(_) => payment_link_conf.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", }, - ) + ), + Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { + message: e.to_string() + })), }) .transpose()?; diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index a6d50fe6156..ef39a34a11e 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -1,14 +1,21 @@ -use api_models::{admin as admin_types, payments::PaymentLinkStatusWrap}; +pub mod validator; +use actix_web::http::header; +use api_models::{ + admin::PaymentLinkConfig, + payments::{PaymentLinkData, PaymentLinkStatusWrap}, +}; use common_utils::{ consts::{ - DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, - DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, DEFAULT_SDK_LAYOUT, DEFAULT_SESSION_EXPIRY, + DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY, + DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, + DEFAULT_SDK_LAYOUT, DEFAULT_SESSION_EXPIRY, }, ext_traits::{OptionExt, ValueExt}, types::{AmountConvertor, MinorUnit, StringMajorUnitForCore}, }; -use error_stack::ResultExt; +use error_stack::{report, ResultExt}; use futures::future; +use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use masking::{PeekInterface, Secret}; use router_env::logger; use time::PrimitiveDateTime; @@ -20,7 +27,9 @@ use crate::{ routes::SessionState, services, types::{ - api::payment_link::PaymentLinkResponseExt, domain, storage::enums as storage_enums, + api::payment_link::PaymentLinkResponseExt, + domain, + storage::{enums as storage_enums, payment_link::PaymentLink}, transformers::ForeignFrom, }, }; @@ -49,17 +58,17 @@ pub async fn retrieve_payment_link( Ok(services::ApplicationResponse::Json(response)) } -pub async fn initiate_payment_link_flow( - state: SessionState, +pub async fn form_payment_link_data( + state: &SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: String, -) -> RouterResponse<services::PaymentLinkFormData> { +) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { let db = &*state.store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( - &(&state).into(), + &(state).into(), &payment_id, &merchant_id, &key_store, @@ -84,21 +93,24 @@ pub async fn initiate_payment_link_flow( .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; - let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config { - extract_payment_link_config(pl_config_value)? - } else { - admin_types::PaymentLinkConfig { - theme: DEFAULT_BACKGROUND_COLOR.to_string(), - logo: DEFAULT_MERCHANT_LOGO.to_string(), - seller_name: merchant_name_from_merchant_account, - sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), - display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, - enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, - } - }; + let payment_link_config = + if let Some(pl_config_value) = payment_link.payment_link_config.clone() { + extract_payment_link_config(pl_config_value)? + } else { + PaymentLinkConfig { + theme: DEFAULT_BACKGROUND_COLOR.to_string(), + logo: DEFAULT_MERCHANT_LOGO.to_string(), + seller_name: merchant_name_from_merchant_account, + sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), + display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, + enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, + allowed_domains: DEFAULT_ALLOWED_DOMAINS, + } + }; let profile_id = payment_link .profile_id + .clone() .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and payment intent")?; @@ -143,7 +155,6 @@ pub async fn initiate_payment_link_flow( // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); - let css_script = get_color_scheme_css(payment_link_config.clone()); let payment_link_status = check_payment_link_status(session_expiry); let is_terminal_state = check_payment_link_invalid_conditions( @@ -205,78 +216,185 @@ pub async fn initiate_payment_link_flow( return_url: return_url.clone(), }; - logger::info!( - "payment link data, for building payment link status page {:?}", - payment_details - ); - let js_script = get_js_script( - &api_models::payments::PaymentLinkData::PaymentLinkStatusDetails(payment_details), - )?; - let payment_link_error_data = services::PaymentLinkStatusData { - js_script, - css_script, - }; - return Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( - services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), - ))); + return Ok(( + payment_link, + PaymentLinkData::PaymentLinkStatusDetails(payment_details), + payment_link_config, + )); }; - let payment_details = api_models::payments::PaymentLinkDetails { - amount, - currency, - payment_id: payment_intent.payment_id, - merchant_name, - order_details, - return_url, - session_expiry, - pub_key: merchant_account.publishable_key, - client_secret, - merchant_logo: payment_link_config.logo.clone(), - max_items_visible_after_collapse: 3, - theme: payment_link_config.theme.clone(), - merchant_description: payment_intent.description, - sdk_layout: payment_link_config.sdk_layout.clone(), - display_sdk_only: payment_link_config.display_sdk_only, - enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method, - }; + let payment_link_details = + PaymentLinkData::PaymentLinkDetails(api_models::payments::PaymentLinkDetails { + amount, + currency, + payment_id: payment_intent.payment_id, + merchant_name, + order_details, + return_url, + session_expiry, + pub_key: merchant_account.publishable_key, + client_secret, + merchant_logo: payment_link_config.logo.clone(), + max_items_visible_after_collapse: 3, + theme: payment_link_config.theme.clone(), + merchant_description: payment_intent.description, + sdk_layout: payment_link_config.sdk_layout.clone(), + display_sdk_only: payment_link_config.display_sdk_only, + }); - let js_script = get_js_script(&api_models::payments::PaymentLinkData::PaymentLinkDetails( - &payment_details, - ))?; + Ok((payment_link, payment_link_details, payment_link_config)) +} + +pub async fn initiate_secure_payment_link_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + merchant_id: common_utils::id_type::MerchantId, + payment_id: String, + request_headers: &header::HeaderMap, +) -> RouterResponse<services::PaymentLinkFormData> { + let (payment_link, payment_link_details, payment_link_config) = + form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id) + .await?; + + validator::validate_secure_payment_link_render_request( + request_headers, + &payment_link, + &payment_link_config, + )?; - let html_meta_tags = get_meta_tags_html(payment_details); + let css_script = get_color_scheme_css(&payment_link_config); + + match payment_link_details { + PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => { + let js_script = get_js_script(&payment_link_details)?; + let payment_link_error_data = services::PaymentLinkStatusData { + js_script, + css_script, + }; + logger::info!( + "payment link data, for building payment link status page {:?}", + status_details + ); + Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( + services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), + ))) + } + PaymentLinkData::PaymentLinkDetails(link_details) => { + let secure_payment_link_details = api_models::payments::SecurePaymentLinkDetails { + enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method, + payment_link_details: link_details.to_owned(), + }; + let js_script = format!( + "window.__PAYMENT_DETAILS = {}", + serde_json::to_string(&secure_payment_link_details) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize PaymentLinkData")? + ); + let html_meta_tags = get_meta_tags_html(&link_details); + let payment_link_data = services::PaymentLinkFormData { + js_script, + sdk_url: state.conf.payment_link.sdk_url.clone(), + css_script, + html_meta_tags, + }; + let allowed_domains = payment_link_config + .allowed_domains + .clone() + .ok_or(report!(errors::ApiErrorResponse::InternalServerError)) + .attach_printable_lazy(|| { + format!( + "Invalid list of allowed_domains found - {:?}", + payment_link_config.allowed_domains.clone() + ) + })?; + + if allowed_domains.is_empty() { + return Err(report!(errors::ApiErrorResponse::InternalServerError)) + .attach_printable_lazy(|| { + format!( + "Invalid list of allowed_domains found - {:?}", + payment_link_config.allowed_domains.clone() + ) + }); + } - let payment_link_data = services::PaymentLinkFormData { - js_script, - sdk_url: state.conf.payment_link.sdk_url.clone(), - css_script, - html_meta_tags, - }; + let link_data = GenericLinks { + allowed_domains, + data: GenericLinksData::SecurePaymentLink(payment_link_data), + }; + logger::info!( + "payment link data, for building secure payment link {:?}", + link_data + ); + + Ok(services::ApplicationResponse::GenericLinkForm(Box::new( + link_data, + ))) + } + } +} - logger::info!( - "payment link data, for building payment link {:?}", - payment_link_data - ); - Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( - services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data), - ))) +pub async fn initiate_payment_link_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + merchant_id: common_utils::id_type::MerchantId, + payment_id: String, +) -> RouterResponse<services::PaymentLinkFormData> { + let (_, payment_details, payment_link_config) = + form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id) + .await?; + + let css_script = get_color_scheme_css(&payment_link_config); + let js_script = get_js_script(&payment_details)?; + + match payment_details { + PaymentLinkData::PaymentLinkStatusDetails(status_details) => { + let payment_link_error_data = services::PaymentLinkStatusData { + js_script, + css_script, + }; + logger::info!( + "payment link data, for building payment link status page {:?}", + status_details + ); + Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( + services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), + ))) + } + PaymentLinkData::PaymentLinkDetails(payment_details) => { + let html_meta_tags = get_meta_tags_html(&payment_details); + let payment_link_data = services::PaymentLinkFormData { + js_script, + sdk_url: state.conf.payment_link.sdk_url.clone(), + css_script, + html_meta_tags, + }; + logger::info!( + "payment link data, for building open payment link {:?}", + payment_link_data + ); + Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( + services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data), + ))) + } + } } /* The get_js_script function is used to inject dynamic value to payment_link sdk, which is unique to every payment. */ -fn get_js_script( - payment_details: &api_models::payments::PaymentLinkData<'_>, -) -> RouterResult<String> { +fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> { let payment_details_str = serde_json::to_string(payment_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};")) } -fn get_color_scheme_css(payment_link_config: api_models::admin::PaymentLinkConfig) -> String { - let background_primary_color = payment_link_config.theme; +fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String { + let background_primary_color = payment_link_config.theme.clone(); format!( ":root {{ --primary-color: {background_primary_color}; @@ -284,12 +402,15 @@ fn get_color_scheme_css(payment_link_config: api_models::admin::PaymentLinkConfi ) } -fn get_meta_tags_html(payment_details: api_models::payments::PaymentLinkDetails) -> String { +fn get_meta_tags_html(payment_details: &api_models::payments::PaymentLinkDetails) -> String { format!( r#"<meta property="og:title" content="Payment request from {0}"/> <meta property="og:description" content="{1}"/>"#, - payment_details.merchant_name, - payment_details.merchant_description.unwrap_or_default() + payment_details.merchant_name.clone(), + payment_details + .merchant_description + .clone() + .unwrap_or_default() ) } @@ -395,11 +516,12 @@ fn validate_order_details( pub fn extract_payment_link_config( pl_config: serde_json::Value, -) -> Result<api_models::admin::PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> { - serde_json::from_value::<api_models::admin::PaymentLinkConfig>(pl_config.clone()) - .change_context(errors::ApiErrorResponse::InvalidDataValue { +) -> Result<PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> { + serde_json::from_value::<PaymentLinkConfig>(pl_config).change_context( + errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", - }) + }, + ) } pub fn get_payment_link_config_based_on_priority( @@ -408,39 +530,39 @@ pub fn get_payment_link_config_based_on_priority( merchant_name: String, default_domain_name: String, payment_link_config_id: Option<String>, -) -> Result<(admin_types::PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> -{ - let (domain_name, business_theme_configs) = if let Some(business_config) = business_link_config - { - let extracted_value: api_models::admin::BusinessPaymentLinkConfig = business_config - .parse_value("BusinessPaymentLinkConfig") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "payment_link_config", - }) - .attach_printable("Invalid payment_link_config given in business config")?; - logger::info!( - "domain name set to custom domain https://{:?}", - extracted_value.domain_name - ); - - ( - extracted_value - .domain_name - .clone() - .map(|d_name| format!("https://{}", d_name)) - .unwrap_or_else(|| default_domain_name.clone()), - payment_link_config_id - .and_then(|id| { - extracted_value - .business_specific_configs - .as_ref() - .and_then(|specific_configs| specific_configs.get(&id).cloned()) +) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> { + let (domain_name, business_theme_configs, allowed_domains) = + if let Some(business_config) = business_link_config { + let extracted_value: api_models::admin::BusinessPaymentLinkConfig = business_config + .parse_value("BusinessPaymentLinkConfig") + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_link_config", }) - .or(extracted_value.default_config), - ) - } else { - (default_domain_name, None) - }; + .attach_printable("Invalid payment_link_config given in business config")?; + logger::info!( + "domain name set to custom domain https://{:?}", + extracted_value.domain_name + ); + + ( + extracted_value + .domain_name + .clone() + .map(|d_name| format!("https://{}", d_name)) + .unwrap_or_else(|| default_domain_name.clone()), + payment_link_config_id + .and_then(|id| { + extracted_value + .business_specific_configs + .as_ref() + .and_then(|specific_configs| specific_configs.get(&id).cloned()) + }) + .or(extracted_value.default_config), + extracted_value.allowed_domains, + ) + } else { + (default_domain_name, None, None) + }; let (theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method) = get_payment_link_config_value!( payment_create_link_config, @@ -456,13 +578,14 @@ pub fn get_payment_link_config_based_on_priority( ) ); - let payment_link_config = admin_types::PaymentLinkConfig { + let payment_link_config = PaymentLinkConfig { theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, + allowed_domains, }; Ok((payment_link_config, domain_name)) @@ -537,13 +660,14 @@ pub async fn get_payment_link_status( let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config { extract_payment_link_config(pl_config_value)? } else { - admin_types::PaymentLinkConfig { + PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, + allowed_domains: DEFAULT_ALLOWED_DOMAINS, } }; @@ -564,7 +688,7 @@ pub async fn get_payment_link_status( // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); - let css_script = get_color_scheme_css(payment_link_config.clone()); + let css_script = get_color_scheme_css(&payment_link_config); let profile_id = payment_link .profile_id @@ -603,9 +727,7 @@ pub async fn get_payment_link_status( theme: payment_link_config.theme.clone(), return_url, }; - let js_script = get_js_script( - &api_models::payments::PaymentLinkData::PaymentLinkStatusDetails(payment_details), - )?; + let js_script = get_js_script(&PaymentLinkData::PaymentLinkStatusDetails(payment_details))?; let payment_link_status_data = services::PaymentLinkStatusData { js_script, css_script, diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html index 1e6723201c9..5e165ac171a 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html @@ -93,7 +93,7 @@ } </style> </head> - <body class="hide-scrollbar"> + <body id="payment-link" class="hide-scrollbar"> <div id="payment-details-shimmer"> <div class = "wrap"> <box class="shine"></box> @@ -324,6 +324,7 @@ </div> <script> {{rendered_js}} + {{payment_link_initiator}} {{logging_template}} </script> {{ hyperloader_sdk_link }} diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index 1a28b6ecf82..48b3de97a81 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -379,75 +379,6 @@ function showSDK(display_sdk_only) { hide("#sdk-spinner"); } -/** - * Trigger - post downloading SDK - * Uses - * - Instantiate SDK - * - Create a payment widget - * - Decide whether or not to show SDK (based on status) - **/ -function initializeSDK() { - // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; - var client_secret = paymentDetails.client_secret; - var appearance = { - variables: { - colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", - fontFamily: "Work Sans, sans-serif", - fontSizeBase: "16px", - colorText: "rgb(51, 65, 85)", - colorTextSecondary: "#334155B3", - colorPrimaryText: "rgb(51, 65, 85)", - colorTextPlaceholder: "#33415550", - borderColor: "#33415550", - colorBackground: "rgb(255, 255, 255)", - }, - }; - // @ts-ignore - hyper = window.Hyper(pub_key, { - isPreloadEnabled: false, - }); - widgets = hyper.widgets({ - appearance: appearance, - clientSecret: client_secret, - }); - var type = - paymentDetails.sdk_layout === "spaced_accordion" || - paymentDetails.sdk_layout === "accordion" - ? "accordion" - : paymentDetails.sdk_layout; - - var enableSavedPaymentMethod = paymentDetails.enabled_saved_payment_method; - var unifiedCheckoutOptions = { - displaySavedPaymentMethodsCheckbox: enableSavedPaymentMethod, - displaySavedPaymentMethods: enableSavedPaymentMethod, - layout: { - type: type, //accordion , tabs, spaced accordion - spacedAccordionItems: paymentDetails.sdk_layout === "spaced_accordion", - }, - branding: "never", - wallets: { - walletReturnUrl: paymentDetails.return_url, - style: { - theme: "dark", - type: "default", - height: 55, - }, - }, - }; - unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions); - mountUnifiedCheckout("#unified-checkout"); - showSDK(paymentDetails.display_sdk_only); - - let shimmer = document.getElementById("payment-details-shimmer"); - shimmer.classList.add("reduce-opacity") - - setTimeout(() => { - document.body.removeChild(shimmer); - }, 500) -} - - /** * Use - mount payment widget on the passed element * @param {String} id @@ -525,17 +456,6 @@ function showMessage(msg) { addText("#payment-message", msg); } -/** - * Use - redirect to /payment_link/status - */ -function redirectToStatus() { - var arr = window.location.pathname.split("/"); - arr.splice(0, 2); - arr.unshift("status"); - arr.unshift("payment_link"); - window.location.href = window.location.origin + "/" + arr.join("/"); -} - function addText(id, msg) { var element = document.querySelector(id); element.innerText = msg; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js new file mode 100644 index 00000000000..4d14af1577c --- /dev/null +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -0,0 +1,82 @@ +// @ts-check + +/** + * Trigger - post downloading SDK + * Uses + * - Instantiate SDK + * - Create a payment widget + * - Decide whether or not to show SDK (based on status) + **/ +function initializeSDK() { + // @ts-ignore + var paymentDetails = window.__PAYMENT_DETAILS; + var client_secret = paymentDetails.client_secret; + var appearance = { + variables: { + colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", + fontFamily: "Work Sans, sans-serif", + fontSizeBase: "16px", + colorText: "rgb(51, 65, 85)", + colorTextSecondary: "#334155B3", + colorPrimaryText: "rgb(51, 65, 85)", + colorTextPlaceholder: "#33415550", + borderColor: "#33415550", + colorBackground: "rgb(255, 255, 255)", + }, + }; + // @ts-ignore + hyper = window.Hyper(pub_key, { + isPreloadEnabled: false, + }); + // @ts-ignore + widgets = hyper.widgets({ + appearance: appearance, + clientSecret: client_secret, + }); + var type = + paymentDetails.sdk_layout === "spaced_accordion" || + paymentDetails.sdk_layout === "accordion" + ? "accordion" + : paymentDetails.sdk_layout; + + var unifiedCheckoutOptions = { + displaySavedPaymentMethodsCheckbox: false, + layout: { + type: type, //accordion , tabs, spaced accordion + spacedAccordionItems: paymentDetails.sdk_layout === "spaced_accordion", + }, + branding: "never", + wallets: { + walletReturnUrl: paymentDetails.return_url, + style: { + theme: "dark", + type: "default", + height: 55, + }, + }, + }; + // @ts-ignore + unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions); + // @ts-ignore + mountUnifiedCheckout("#unified-checkout"); + // @ts-ignore + showSDK(paymentDetails.display_sdk_only); + + let shimmer = document.getElementById("payment-details-shimmer"); + shimmer.classList.add("reduce-opacity"); + + setTimeout(() => { + document.body.removeChild(shimmer); + }, 500); + + /** + * Use - redirect to /payment_link/status + */ + function redirectToStatus() { + var arr = window.location.pathname.split("/"); + arr.splice(0, 2); + arr.unshift("status"); + arr.unshift("payment_link"); + window.location.href = window.location.origin + "/" + arr.join("/"); + } +} diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js new file mode 100644 index 00000000000..7a75afc1d8e --- /dev/null +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -0,0 +1,107 @@ +// @ts-check + +// Top level checks +var isFramed = false; +try { + isFramed = window.parent.location !== window.location; + + // If parent's window object is restricted, DOMException is + // thrown which concludes that the webpage is iframed +} catch (err) { + isFramed = true; +} + +if (!isFramed) { + function initializeSDK() { + var errMsg = "You are not allowed to view this content."; + var contentElement = document.getElementById("payment-link"); + if (contentElement instanceof HTMLDivElement) { + contentElement.innerHTML = errMsg; + } else { + document.body.innerHTML = errMsg; + } + } +} else { + /** + * Trigger - post downloading SDK + * Uses + * - Instantiate SDK + * - Create a payment widget + * - Decide whether or not to show SDK (based on status) + **/ + function initializeSDK() { + // @ts-ignore + var paymentDetails = window.__PAYMENT_DETAILS; + var client_secret = paymentDetails.client_secret; + var appearance = { + variables: { + colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", + fontFamily: "Work Sans, sans-serif", + fontSizeBase: "16px", + colorText: "rgb(51, 65, 85)", + colorTextSecondary: "#334155B3", + colorPrimaryText: "rgb(51, 65, 85)", + colorTextPlaceholder: "#33415550", + borderColor: "#33415550", + colorBackground: "rgb(255, 255, 255)", + }, + }; + // @ts-ignore + hyper = window.Hyper(pub_key, { + isPreloadEnabled: false, + }); + // @ts-ignore + widgets = hyper.widgets({ + appearance: appearance, + clientSecret: client_secret, + }); + var type = + paymentDetails.sdk_layout === "spaced_accordion" || + paymentDetails.sdk_layout === "accordion" + ? "accordion" + : paymentDetails.sdk_layout; + + var enableSavedPaymentMethod = paymentDetails.enabled_saved_payment_method; + var unifiedCheckoutOptions = { + displaySavedPaymentMethodsCheckbox: enableSavedPaymentMethod, + displaySavedPaymentMethods: enableSavedPaymentMethod, + layout: { + type: type, //accordion , tabs, spaced accordion + spacedAccordionItems: paymentDetails.sdk_layout === "spaced_accordion", + }, + branding: "never", + wallets: { + walletReturnUrl: paymentDetails.return_url, + style: { + theme: "dark", + type: "default", + height: 55, + }, + }, + }; + // @ts-ignore + unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions); + // @ts-ignore + mountUnifiedCheckout("#unified-checkout"); + // @ts-ignore + showSDK(paymentDetails.display_sdk_only); + + let shimmer = document.getElementById("payment-details-shimmer"); + shimmer.classList.add("reduce-opacity"); + + setTimeout(() => { + document.body.removeChild(shimmer); + }, 500); + } + + /** + * Use - redirect to /payment_link/status + */ + function redirectToStatus() { + var arr = window.location.pathname.split("/"); + arr.splice(0, 3); + arr.unshift("status"); + arr.unshift("payment_link"); + window.location.href = window.location.origin + "/" + arr.join("/"); + } +} diff --git a/crates/router/src/core/payment_link/validator.rs b/crates/router/src/core/payment_link/validator.rs new file mode 100644 index 00000000000..0968c8301aa --- /dev/null +++ b/crates/router/src/core/payment_link/validator.rs @@ -0,0 +1,118 @@ +use actix_http::header; +use api_models::admin::PaymentLinkConfig; +use common_utils::validation::validate_domain_against_allowed_domains; +use error_stack::{report, ResultExt}; +use url::Url; + +use crate::{ + core::errors::{self, RouterResult}, + types::storage::PaymentLink, +}; + +pub fn validate_secure_payment_link_render_request( + request_headers: &header::HeaderMap, + payment_link: &PaymentLink, + payment_link_config: &PaymentLinkConfig, +) -> RouterResult<()> { + let link_id = payment_link.payment_link_id.clone(); + let allowed_domains = payment_link_config + .allowed_domains + .clone() + .ok_or(report!(errors::ApiErrorResponse::InvalidRequestUrl)) + .attach_printable_lazy(|| { + format!( + "Secure payment link was not generated for {}\nmissing allowed_domains", + link_id + ) + })?; + + // Validate secure_link was generated + if payment_link.secure_link.clone().is_none() { + return Err(report!(errors::ApiErrorResponse::InvalidRequestUrl)).attach_printable_lazy( + || { + format!( + "Secure payment link was not generated for {}\nmissing secure_link", + link_id + ) + }, + ); + } + + // Fetch destination is "iframe" + match request_headers.get("sec-fetch-dest").and_then(|v| v.to_str().ok()) { + Some("iframe") => Ok(()), + Some(requestor) => Err(report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payment_link".to_string(), + })) + .attach_printable_lazy(|| { + format!( + "Access to payment_link [{}] is forbidden when requested through {}", + link_id, requestor + ) + }), + None => Err(report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payment_link".to_string(), + })) + .attach_printable_lazy(|| { + format!( + "Access to payment_link [{}] is forbidden when sec-fetch-dest is not present in request headers", + link_id + ) + }), + }?; + + // Validate origin / referer + let domain_in_req = { + let origin_or_referer = request_headers + .get("origin") + .or_else(|| request_headers.get("referer")) + .and_then(|v| v.to_str().ok()) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payment_link".to_string(), + }) + }) + .attach_printable_lazy(|| { + format!( + "Access to payment_link [{}] is forbidden when origin or referer is not present in request headers", + link_id + ) + })?; + + let url = Url::parse(origin_or_referer) + .map_err(|_| { + report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payment_link".to_string(), + }) + }) + .attach_printable_lazy(|| { + format!("Invalid URL found in request headers {}", origin_or_referer) + })?; + + url.host_str() + .and_then(|host| url.port().map(|port| format!("{}:{}", host, port))) + .or_else(|| url.host_str().map(String::from)) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payment_link".to_string(), + }) + }) + .attach_printable_lazy(|| { + format!("host or port not found in request headers {:?}", url) + })? + }; + + if validate_domain_against_allowed_domains(&domain_in_req, allowed_domains) { + Ok(()) + } else { + Err(report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payment_link".to_string(), + })) + .attach_printable_lazy(|| { + format!( + "Access to payment_link [{}] is forbidden from requestor - {}", + link_id, domain_in_req + ) + }) + } +} diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index b7f86b6838a..07233be3996 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1218,13 +1218,22 @@ async fn create_payment_link( ) -> RouterResult<Option<api_models::payments::PaymentLinkResponse>> { let created_at @ last_modified_at = Some(common_utils::date_time::now()); let payment_link_id = utils::generate_id(consts::ID_LENGTH, "plink"); - let payment_link = format!( + let open_payment_link = format!( "{}/payment_link/{}/{}", domain_name, merchant_id.get_string_repr(), payment_id.clone() ); + let secure_link = payment_link_config.allowed_domains.as_ref().map(|_| { + format!( + "{}/payment_link/s/{}/{}", + domain_name, + merchant_id.clone(), + payment_id.clone() + ) + }); + let payment_link_config_encoded_value = payment_link_config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", @@ -1235,7 +1244,7 @@ async fn create_payment_link( payment_link_id: payment_link_id.clone(), payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), - link_to_pay: payment_link.clone(), + link_to_pay: open_payment_link.clone(), amount: MinorUnit::from(amount), currency: request.currency, created_at, @@ -1245,6 +1254,7 @@ async fn create_payment_link( description, payment_link_config: Some(payment_link_config_encoded_value), profile_id: Some(profile_id), + secure_link, }; let payment_link_db = db .insert_payment_link(payment_link_req) @@ -1254,7 +1264,8 @@ async fn create_payment_link( })?; Ok(Some(api_models::payments::PaymentLinkResponse { - link: payment_link_db.link_to_pay, + link: payment_link_db.link_to_pay.clone(), + secure_link: payment_link_db.secure_link, payment_link_id: payment_link_db.payment_link_id, })) } diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs index 7d5b8c05ee2..f9a2939eb08 100644 --- a/crates/router/src/core/payouts/validator.rs +++ b/crates/router/src/core/payouts/validator.rs @@ -1,13 +1,11 @@ -use std::collections::HashSet; - use actix_web::http::header; #[cfg(feature = "olap")] use common_utils::errors::CustomResult; +use common_utils::validation::validate_domain_against_allowed_domains; use diesel_models::generic_link::PayoutLink; use error_stack::{report, ResultExt}; -use globset::Glob; pub use hyperswitch_domain_models::errors::StorageError; -use router_env::{instrument, logger, tracing}; +use router_env::{instrument, tracing}; use url::Url; use super::helpers; @@ -255,7 +253,7 @@ pub fn validate_payout_link_render_request( })? }; - if is_domain_allowed(&domain_in_req, link_data.allowed_domains) { + if validate_domain_against_allowed_domains(&domain_in_req, link_data.allowed_domains) { Ok(()) } else { Err(report!(errors::ApiErrorResponse::AccessForbidden { @@ -269,12 +267,3 @@ pub fn validate_payout_link_render_request( }) } } - -fn is_domain_allowed(domain: &str, allowed_domains: HashSet<String>) -> bool { - allowed_domains.iter().any(|allowed_domain| { - Glob::new(allowed_domain) - .map(|glob| glob.compile_matcher().is_match(domain)) - .map_err(|err| logger::error!("Invalid glob pattern! - {:?}", err)) - .unwrap_or(false) - }) -} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0e1be147fbd..76b4270a058 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1341,6 +1341,10 @@ impl PaymentLink { web::resource("{merchant_id}/{payment_id}") .route(web::get().to(initiate_payment_link)), ) + .service( + web::resource("s/{merchant_id}/{payment_id}") + .route(web::get().to(initiate_secure_payment_link)), + ) .service( web::resource("status/{merchant_id}/{payment_id}") .route(web::get().to(payment_link_status)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9618971e52d..9f073853d88 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -188,6 +188,7 @@ impl From<Flow> for ApiIdentifier { Flow::PaymentLinkRetrieve | Flow::PaymentLinkInitiate + | Flow::PaymentSecureLinkInitiate | Flow::PaymentLinkList | Flow::PaymentLinkStatus => Self::PaymentLink, diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs index 33d3c21ef9f..b1be7091151 100644 --- a/crates/router/src/routes/payment_link.rs +++ b/crates/router/src/routes/payment_link.rs @@ -82,6 +82,39 @@ pub async fn initiate_payment_link( .await } +pub async fn initiate_secure_payment_link( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + path: web::Path<(common_utils::id_type::MerchantId, String)>, +) -> impl Responder { + let flow = Flow::PaymentSecureLinkInitiate; + let (merchant_id, payment_id) = path.into_inner(); + let payload = api_models::payments::PaymentLinkInitiateRequest { + payment_id, + merchant_id: merchant_id.clone(), + }; + let headers = req.headers(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload.clone(), + |state, auth, _, _| { + initiate_secure_payment_link_flow( + state, + auth.merchant_account, + auth.key_store, + payload.merchant_id.clone(), + payload.payment_id.clone(), + headers, + ) + }, + &crate::services::authentication::MerchantIdAuth(merchant_id), + api_locking::LockAction::NotApplicable, + )) + .await +} + /// Payment Link - List /// /// To list the payment links diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 129be81e41e..a973d855733 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -47,7 +47,7 @@ use masking::{Maskable, PeekInterface}; use router_env::{instrument, metrics::add_attributes, tracing, tracing_actix_web::RequestId, Tag}; use serde::Serialize; use serde_json::json; -use tera::{Context, Tera}; +use tera::{Context, Error as TeraError, Tera}; use self::request::{HeaderExt, RequestBuilderExt}; use super::{ @@ -1058,14 +1058,18 @@ where let link_type = boxed_generic_link_data.data.to_string(); match build_generic_link_html(boxed_generic_link_data.data) { Ok(rendered_html) => { - let domains_str = boxed_generic_link_data - .allowed_domains - .into_iter() - .collect::<Vec<String>>() - .join(" "); - let csp_header = format!("frame-ancestors 'self' {};", domains_str); - let headers = HashSet::from([("content-security-policy", csp_header)]); - http_response_html_data(rendered_html, Some(headers)) + let headers = if !boxed_generic_link_data.allowed_domains.is_empty() { + let domains_str = boxed_generic_link_data + .allowed_domains + .into_iter() + .collect::<Vec<String>>() + .join(" "); + let csp_header = format!("frame-ancestors 'self' {};", domains_str); + Some(HashSet::from([("content-security-policy", csp_header)])) + } else { + None + }; + http_response_html_data(rendered_html, headers) } Err(_) => { http_response_err(format!("Error while rendering {} HTML page", link_type)) @@ -1863,9 +1867,9 @@ pub fn build_redirection_form( } } -pub fn build_payment_link_html( +fn build_payment_link_template( payment_link_data: PaymentLinkFormData, -) -> CustomResult<String, errors::ApiErrorResponse> { +) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> { let mut tera = Tera::default(); // Add modification to css template with dynamic data @@ -1916,11 +1920,6 @@ pub fn build_payment_link_html( &get_preload_link_html_template(&payment_link_data.sdk_url), ); - context.insert( - "preload_link_tags", - &get_preload_link_html_template(&payment_link_data.sdk_url), - ); - context.insert( "hyperloader_sdk_link", &get_hyper_loader_sdk(&payment_link_data.sdk_url), @@ -1930,13 +1929,43 @@ pub fn build_payment_link_html( context.insert("logging_template", &logging_template); - match tera.render("payment_link", &context) { - Ok(rendered_html) => Ok(rendered_html), - Err(tera_error) => { + Ok((tera, context)) +} + +pub fn build_payment_link_html( + payment_link_data: PaymentLinkFormData, +) -> CustomResult<String, errors::ApiErrorResponse> { + let (tera, mut context) = build_payment_link_template(payment_link_data) + .attach_printable("Failed to build payment link's HTML template")?; + let payment_link_initiator = + include_str!("../core/payment_link/payment_link_initiate/payment_link_initiator.js") + .to_string(); + context.insert("payment_link_initiator", &payment_link_initiator); + + tera.render("payment_link", &context) + .map_err(|tera_error: TeraError| { crate::logger::warn!("{tera_error}"); - Err(errors::ApiErrorResponse::InternalServerError)? - } - } + report!(errors::ApiErrorResponse::InternalServerError) + }) + .attach_printable("Error while rendering open payment link's HTML template") +} + +pub fn build_secure_payment_link_html( + payment_link_data: PaymentLinkFormData, +) -> CustomResult<String, errors::ApiErrorResponse> { + let (tera, mut context) = build_payment_link_template(payment_link_data) + .attach_printable("Failed to build payment link's HTML template")?; + let payment_link_initiator = + include_str!("../core/payment_link/payment_link_initiate/secure_payment_link_initiator.js") + .to_string(); + context.insert("payment_link_initiator", &payment_link_initiator); + + tera.render("payment_link", &context) + .map_err(|tera_error: TeraError| { + crate::logger::warn!("{tera_error}"); + report!(errors::ApiErrorResponse::InternalServerError) + }) + .attach_printable("Error while rendering secure payment link's HTML template") } fn get_hyper_loader_sdk(sdk_url: &str) -> String { diff --git a/crates/router/src/services/api/generic_link_response.rs b/crates/router/src/services/api/generic_link_response.rs index 497926481ab..f180e3d3f33 100644 --- a/crates/router/src/services/api/generic_link_response.rs +++ b/crates/router/src/services/api/generic_link_response.rs @@ -5,6 +5,7 @@ use hyperswitch_domain_models::api::{ }; use tera::{Context, Tera}; +use super::build_secure_payment_link_html; use crate::core::errors; pub fn build_generic_link_html( @@ -24,6 +25,9 @@ pub fn build_generic_link_html( GenericLinksData::PayoutLinkStatus(pm_collect_data) => { build_payout_link_status_html(&pm_collect_data) } + GenericLinksData::SecurePaymentLink(payment_link_data) => { + build_secure_payment_link_html(payment_link_data) + } } } @@ -45,46 +49,58 @@ pub fn build_generic_expired_link_html( .attach_printable("Failed to render expired link HTML template") } -pub fn build_payout_link_html( +fn build_html_template( link_data: &GenericLinkFormData, -) -> CustomResult<String, errors::ApiErrorResponse> { - let mut tera = Tera::default(); + document: &'static str, + script: &'static str, + styles: &'static str, +) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> { + let mut tera: Tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; - let css_template = - include_str!("../../core/generic_link/payout_link/initiate/styles.css").to_string(); + let css_template = styles.to_string(); let final_css = format!("{}\n{}", css_dynamic_context, css_template); - let _ = tera.add_raw_template("payout_link_styles", &final_css); + let _ = tera.add_raw_template("document_styles", &final_css); context.insert("color_scheme", &link_data.css_data); + // Insert dynamic context in JS + let js_dynamic_context = "{{ script_data }}"; + let js_template = script.to_string(); + let final_js = format!("{}\n{}", js_dynamic_context, js_template); + let _ = tera.add_raw_template("document_scripts", &final_js); + context.insert("script_data", &link_data.js_data); + let css_style_tag = tera - .render("payout_link_styles", &context) + .render("document_styles", &context) .map(|css| format!("<style>{}</style>", css)) .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to render payout link's CSS template")?; - - // Insert dynamic context in JS - let js_dynamic_context = "{{ payout_link_context }}"; - let js_template = - include_str!("../../core/generic_link/payout_link/initiate/script.js").to_string(); - let final_js = format!("{}\n{}", js_dynamic_context, js_template); - let _ = tera.add_raw_template("payout_link_script", &final_js); - context.insert("payout_link_context", &link_data.js_data); + .attach_printable("Failed to render CSS template")?; let js_script_tag = tera - .render("payout_link_script", &context) + .render("document_scripts", &context) .map(|js| format!("<script>{}</script>", js)) .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to render payout link's JS template")?; + .attach_printable("Failed to render JS template")?; - // Build HTML - let html_template = - include_str!("../../core/generic_link/payout_link/initiate/index.html").to_string(); - let _ = tera.add_raw_template("payout_link", &html_template); + // Insert HTML context + let html_template = document.to_string(); + let _ = tera.add_raw_template("html_template", &html_template); context.insert("css_style_tag", &css_style_tag); context.insert("js_script_tag", &js_script_tag); + + Ok((tera, context)) +} + +pub fn build_payout_link_html( + link_data: &GenericLinkFormData, +) -> CustomResult<String, errors::ApiErrorResponse> { + let document = include_str!("../../core/generic_link/payout_link/initiate/index.html"); + let script = include_str!("../../core/generic_link/payout_link/initiate/script.js"); + let styles = include_str!("../../core/generic_link/payout_link/initiate/styles.css"); + let (tera, mut context) = build_html_template(link_data, document, script, styles) + .attach_printable("Failed to build context for payout link's HTML template")?; context.insert( "hyper_sdk_loader_script_tag", &format!( @@ -93,7 +109,7 @@ pub fn build_payout_link_html( ), ); - tera.render("payout_link", &context) + tera.render("html_template", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link's HTML template") } @@ -101,46 +117,14 @@ pub fn build_payout_link_html( pub fn build_pm_collect_link_html( link_data: &GenericLinkFormData, ) -> CustomResult<String, errors::ApiErrorResponse> { - let mut tera = Tera::default(); - let mut context = Context::new(); - - // Insert dynamic context in CSS - let css_dynamic_context = "{{ color_scheme }}"; - let css_template = - include_str!("../../core/generic_link/payment_method_collect/initiate/styles.css") - .to_string(); - let final_css = format!("{}\n{}", css_dynamic_context, css_template); - let _ = tera.add_raw_template("pm_collect_link_styles", &final_css); - context.insert("color_scheme", &link_data.css_data); - - let css_style_tag = tera - .render("pm_collect_link_styles", &context) - .map(|css| format!("<style>{}</style>", css)) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to render payment method collect link's CSS template")?; - - // Insert dynamic context in JS - let js_dynamic_context = "{{ collect_link_context }}"; - let js_template = - include_str!("../../core/generic_link/payment_method_collect/initiate/script.js") - .to_string(); - let final_js = format!("{}\n{}", js_dynamic_context, js_template); - let _ = tera.add_raw_template("pm_collect_link_script", &final_js); - context.insert("collect_link_context", &link_data.js_data); - - let js_script_tag = tera - .render("pm_collect_link_script", &context) - .map(|js| format!("<script>{}</script>", js)) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to render payment method collect link's JS template")?; - - // Build HTML - let html_template = - include_str!("../../core/generic_link/payment_method_collect/initiate/index.html") - .to_string(); - let _ = tera.add_raw_template("payment_method_collect_link", &html_template); - context.insert("css_style_tag", &css_style_tag); - context.insert("js_script_tag", &js_script_tag); + let document = + include_str!("../../core/generic_link/payment_method_collect/initiate/index.html"); + let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js"); + let styles = include_str!("../../core/generic_link/payment_method_collect/initiate/styles.css"); + let (tera, mut context) = build_html_template(link_data, document, script, styles) + .attach_printable( + "Failed to build context for payment method collect link's HTML template", + )?; context.insert( "hyper_sdk_loader_script_tag", &format!( @@ -149,7 +133,7 @@ pub fn build_pm_collect_link_html( ), ); - tera.render("payment_method_collect_link", &context) + tera.render("html_template", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link's HTML template") } diff --git a/crates/router/src/types/api/payment_link.rs b/crates/router/src/types/api/payment_link.rs index 85cb539d411..3d50db35fc4 100644 --- a/crates/router/src/types/api/payment_link.rs +++ b/crates/router/src/types/api/payment_link.rs @@ -30,6 +30,7 @@ impl PaymentLinkResponseExt for RetrievePaymentLinkResponse { expiry: payment_link.fulfilment_time, currency: payment_link.currency, status, + secure_link: payment_link.secure_link, }) } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 8a29ac7e79a..a510a26151b 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1289,6 +1289,7 @@ impl ForeignFrom<(storage::PaymentLink, payments::PaymentLinkStatus)> description: payment_link_config.description, currency: payment_link_config.currency, status, + secure_link: payment_link_config.secure_link, } } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index cefc2fbd1d0..f1d2e5d8dcc 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -290,6 +290,8 @@ pub enum Flow { PaymentLinkRetrieve, /// payment Link Initiate flow PaymentLinkInitiate, + /// payment Link Initiate flow + PaymentSecureLinkInitiate, /// Payment Link List flow PaymentLinkList, /// Payment Link Status diff --git a/migrations/2024-07-17-131830_alter_payment_link/down.sql b/migrations/2024-07-17-131830_alter_payment_link/down.sql new file mode 100644 index 00000000000..db8d02eb036 --- /dev/null +++ b/migrations/2024-07-17-131830_alter_payment_link/down.sql @@ -0,0 +1 @@ +ALTER table payment_link DROP COLUMN IF EXISTS secure_link; \ No newline at end of file diff --git a/migrations/2024-07-17-131830_alter_payment_link/up.sql b/migrations/2024-07-17-131830_alter_payment_link/up.sql new file mode 100644 index 00000000000..979c92a0ac7 --- /dev/null +++ b/migrations/2024-07-17-131830_alter_payment_link/up.sql @@ -0,0 +1,2 @@ +-- Add a new column for allowed domains and secure link endpoint +ALTER table payment_link ADD COLUMN IF NOT EXISTS secure_link VARCHAR(255); \ No newline at end of file
2024-07-18T06:54:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Described in https://github.com/juspay/hyperswitch/issues/5372 ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? Tested locally using postman collection. Expectations - - existing payment links is available as open links (cannot list SPMs or render checkbox to store PM) - secure links are generated only when allowed_domains are configured - secure links can only be accessed from within an iframe on the allowed domains #### Open links <details> <summary>1. Create a payment link - (unfold to view cURL)</summary> curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_eBTVu8OMN1HmE2xr0I0dsfypWOVwQBlietvkxf0sgYMdyFM5nRO40M8M4MLH42Jk' \ --data '{ "customer_id": "cus_izAOZiynP5URGEvEfmgH", "amount": 100, "currency": "USD", "payment_link": true, "connector": [ "stripe" ], "session_expiry": 1000000, "return_url": "http://127.0.0.1:5500/src/pl_iframe.html", "payment_link_config": { "theme": "#14356f", "logo": "https://logosandtypes.com/wp-content/uploads/2020/08/zurich.svg", "seller_name": "Zurich Inc." } }' </details> 2. Open the payment link (`link` in API response) and validate the functionality #### Secure links <details> <summary>1. Update `allowed_domains` in business profile - (unfold to view cURL)</summary> curl --location 'http://localhost:8080/account/merchant_1721984694/business_profile/pro_oXHnmgfZSnfe92PvodqP' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "payment_link_config": { "allowed_domains": [ "*" ], "enabled_saved_payment_method": true } }' </details> <details> <summary>2. Create a payment link - (unfold to view cURL)</summary> curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_eBTVu8OMN1HmE2xr0I0dsfypWOVwQBlietvkxf0sgYMdyFM5nRO40M8M4MLH42Jk' \ --data '{ "customer_id": "cus_izAOZiynP5URGEvEfmgH", "amount": 100, "currency": "USD", "payment_link": true, "connector": [ "stripe" ], "session_expiry": 1000000, "return_url": "http://127.0.0.1:5500/src/pl_iframe.html", "payment_link_config": { "theme": "#14356f", "logo": "https://logosandtypes.com/wp-content/uploads/2020/08/zurich.svg", "seller_name": "Zurich Inc." } }' </details> 3. Open the secure payment link (`secure_link` in API response) in an iframe for validating the functionality #### Secure links demo [Screencast from 26-07-24 02:34:52 PM IST.webm](https://github.com/user-attachments/assets/fca25275-fcb3-49cf-9fc5-967884b635d2) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0f89a0acbfc2d55f415e0daeb27e8d9022e6a862
juspay/hyperswitch
juspay__hyperswitch-5339
Bug: do not update `perform_session_flow_routing` output if the `SessionRoutingChoice` is none While performing the session token routing we create an empty vec that will contain the Routing choices for that particular session. In case if there is no connectors that requires session call then the `perform_session_flow_routing` will return the empty vec. Instead if there is no connectors that requires session call, then we should just return empty hashmap.
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index d1a5441d958..d6904e09a3d 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1009,7 +1009,9 @@ pub async fn perform_session_flow_routing( }); } } - result.insert(pm_type, session_routing_choice); + if !session_routing_choice.is_empty() { + result.insert(pm_type, session_routing_choice); + } } }
2024-07-16T10:56:21Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> While performing the session token routing we create an empty vec that will contain the Routing choices for that particular session. In case if there is no connectors that requires session call then the `perform_session_flow_routing` will return the empty vec. Instead if there is no connectors that requires session call, then we should just return empty hashmap. https://github.com/juspay/hyperswitch/pull/5336 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create mca for stripe with apple pay, google pay and klarna ``` { "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "==", "display_name": "applepay", "certificate_keys": "", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "", "payment_processing_certificate_key": "", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ] } } } ``` <img width="1089" alt="image" src="https://github.com/user-attachments/assets/f312ee05-60be-41b7-bf2e-a0a83b15a524"> -> Also enable klarna via klarna -> Now configure volume based routing for the connector -> Create a payment and make a session call ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_1l8FEkupRHGMJp9gZyj9HDUwgsSgAVgiKjtvdiDfocYs5Gjo2cn3UTpjNTBzYRHH' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1720854397" }' ``` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Safari' \ --header 'x-client-platform: web' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key: pk_dev_2a79cad91c884bc7bb425a9822d09d0b' \ --data '{ "payment_id": "pay_wp2gnnTNuK1oxMF2T6Yf", "wallets": [], "client_secret": "pay_wp2gnnTNuK1oxMF2T6Yf_secret_T10Mxvzq3hqBWfxOfIJI" }' ``` <img width="1092" alt="image" src="https://github.com/user-attachments/assets/7c1af753-2cc9-46f0-bd01-bfc81ebeb81b"> -> Now disable klarna for stripe, create a payment and make a session call. <img width="1152" alt="image" src="https://github.com/user-attachments/assets/19304947-400c-453e-bb6d-e2affe03927a"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
419344eb32cdd206033a64d0e4b53e6382c73a4e
juspay/hyperswitch
juspay__hyperswitch-5337
Bug: do not update `perform_session_flow_routing` output if the `SessionRoutingChoice` is none While performing the session token routing we create an empty vec that will contain the Routing choices for that particular session. In case if there is no connectors that requires session call then the `perform_session_flow_routing` will return the empty vec. Instead if there is no connectors that requires session call, then we should just return empty hashmap.
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index d1a5441d958..d6904e09a3d 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1009,7 +1009,9 @@ pub async fn perform_session_flow_routing( }); } } - result.insert(pm_type, session_routing_choice); + if !session_routing_choice.is_empty() { + result.insert(pm_type, session_routing_choice); + } } }
2024-07-16T09:34:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> While performing the session token routing we create an empty vec that will contain the Routing choices for that particular session. In case if there is no connectors that requires session call then the `perform_session_flow_routing` will return the empty vec. Instead if there is no connectors that requires session call, then we should just return empty hashmap. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create mca for stripe with apple pay, google pay and klarna ``` { "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "==", "display_name": "applepay", "certificate_keys": "", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "", "payment_processing_certificate_key": "", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ] } } } ``` <img width="1089" alt="image" src="https://github.com/user-attachments/assets/f312ee05-60be-41b7-bf2e-a0a83b15a524"> -> Also enable klarna via klarna -> Now configure volume based routing for the connector -> Create a payment and make a session call ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_1l8FEkupRHGMJp9gZyj9HDUwgsSgAVgiKjtvdiDfocYs5Gjo2cn3UTpjNTBzYRHH' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1720854397" }' ``` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Safari' \ --header 'x-client-platform: web' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key: pk_dev_2a79cad91c884bc7bb425a9822d09d0b' \ --data '{ "payment_id": "pay_wp2gnnTNuK1oxMF2T6Yf", "wallets": [], "client_secret": "pay_wp2gnnTNuK1oxMF2T6Yf_secret_T10Mxvzq3hqBWfxOfIJI" }' ``` <img width="1092" alt="image" src="https://github.com/user-attachments/assets/7c1af753-2cc9-46f0-bd01-bfc81ebeb81b"> -> Now disable klarna for stripe, create a payment and make a session call. <img width="1152" alt="image" src="https://github.com/user-attachments/assets/19304947-400c-453e-bb6d-e2affe03927a"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
3951ac6578359c62a9b12582f5a5bbeef4c1b769
juspay/hyperswitch
juspay__hyperswitch-5340
Bug: feat(globalsearch): Add search_tags based filter for global search in dashboard Add a filter based on `search_tags` for global search in dashboard The search_tags must be hashed before pushing them to kafka payment-intent events and opensearch.
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index 269864bf44a..a5bd117bd63 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -66,6 +66,24 @@ pub async fn msearch_results( .switch()?; } }; + if let Some(search_tags) = filters.search_tags { + if !search_tags.is_empty() { + query_builder + .add_filter_clause( + "feature_metadata.search_tags.keyword".to_string(), + search_tags + .iter() + .filter_map(|search_tag| { + // TODO: Add trait based inputs instead of converting this to strings + serde_json::to_value(search_tag) + .ok() + .and_then(|a| a.as_str().map(|a| a.to_string())) + }) + .collect(), + ) + .switch()?; + } + }; }; let response_text: OpenMsearchOutput = client @@ -173,6 +191,24 @@ pub async fn search_results( .switch()?; } }; + if let Some(search_tags) = filters.search_tags { + if !search_tags.is_empty() { + query_builder + .add_filter_clause( + "feature_metadata.search_tags.keyword".to_string(), + search_tags + .iter() + .filter_map(|search_tag| { + // TODO: Add trait based inputs instead of converting this to strings + serde_json::to_value(search_tag) + .ok() + .and_then(|a| a.as_str().map(|a| a.to_string())) + }) + .collect(), + ) + .switch()?; + } + }; }; query_builder .set_offset_n_count(search_req.offset, search_req.count) diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index 034a2a94356..d1af00de569 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -1,4 +1,5 @@ use common_utils::hashing::HashedString; +use masking::WithType; use serde_json::Value; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] @@ -7,6 +8,7 @@ pub struct SearchFilters { pub currency: Option<Vec<String>>, pub status: Option<Vec<String>>, pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>, + pub search_tags: Option<Vec<HashedString<WithType>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index bcc67100e1c..bf39e3d6dd5 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -9,11 +9,12 @@ use common_utils::{ consts::default_payments_list_limit, crypto, ext_traits::{ConfigExt, Encode}, + hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; -use masking::{PeekInterface, Secret}; +use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{ de::{self, Unexpected, Visitor}, @@ -4955,11 +4956,12 @@ pub struct PaymentsStartRequest { #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios + #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, // TODO: Convert this to hashedstrings to avoid PII sensitive data /// Additional tags to be used for global search - #[schema(value_type = Option<RedirectResponse>)] - pub search_tags: Option<Vec<Secret<String>>>, + #[schema(value_type = Option<Vec<String>>)] + pub search_tags: Option<Vec<HashedString<WithType>>>, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None diff --git a/crates/masking/src/strategy.rs b/crates/masking/src/strategy.rs index 8b4d9b0ec34..eb705ca490a 100644 --- a/crates/masking/src/strategy.rs +++ b/crates/masking/src/strategy.rs @@ -7,6 +7,8 @@ pub trait Strategy<T> { } /// Debug with type +#[cfg_attr(feature = "serde", derive(serde::Deserialize))] +#[derive(Debug, Copy, Clone)] pub enum WithType {} impl<T> Strategy<T> for WithType {
2024-07-16T12:10:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Added a filter based on `search_tags` in `feature_metadata` for global search in dashboard - The `search_tags` are hashed before pushing them to kafka payment-intent events and opensearch. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Better and strict search experience, based on `search_tags` present in `feature_metadata` ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested through curls in postman: - Payment: ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_IG9ateOUhGE0KLFEItNN1tsJXcr5M62N7zlbtOlUtStTfPpzSomswbQa4aO2k1B4' \ --data-raw '{ "amount": 6540, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "test@test2.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_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" }, "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", "feature_metadata": { "search_tags": ["lucknow", "Kolkata"] }, "metadata": { "data2": "camel", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` <img width="1373" alt="Screenshot 2024-07-16 at 5 36 53 PM" src="https://github.com/user-attachments/assets/6fe1860e-1fe6-4941-86c9-0cb15d752f99"> <img width="1712" alt="Screenshot 2024-07-16 at 5 37 41 PM" src="https://github.com/user-attachments/assets/cbe2b79c-f194-4dd7-9914-4ef771c0908f"> - Search based on filters: ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGU2ZWVhYzEtMWVjNi00ZWQyLWJhY2YtMDUzOTFiZGE3YjI1IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzE5OTA0MzA1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMTIxMTIwOCwib3JnX2lkIjoib3JnX0c4Zk85a09UTXl1OHBXUEVQSUcwIn0.hLDGqg8n0ygYHKbZU-mmcD8f78GOFjZiuPOlwKi_zCs' \ --header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data-raw '{ "query": "merchant_1719904305", "filters": { "customer_email": [ "test@test2.com" ], "currency": [ "INR" ], "search_tags": [ "lucknow" ] } }' ``` <img width="737" alt="Screenshot 2024-07-16 at 5 39 52 PM" src="https://github.com/user-attachments/assets/4ae84f9c-531e-4149-988e-fe40a6421c90"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
949e84e88fcb58db388bef536e89ab0510f5ede9
juspay/hyperswitch
juspay__hyperswitch-5344
Bug: Adding contributors guide Adding contributors guide
diff --git a/README.md b/README.md index 62e016d3620..a54c4ea7ea2 100644 --- a/README.md +++ b/README.md @@ -9,19 +9,20 @@ The single API to access payment ecosystems across 130+ countries</div> <p align="center"> - <a href="#%EF%B8%8F-quick-start-guide">Quick Start Guide</a> • - <a href="/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> • - <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> + <a href="#try-a-payment">Try a Payment</a> • + <a href="#for-enterprises">For Enterprises</a> • + <a href="#for-contributors">For Contributors</a> • + <a href="#quick-setup">Quick Setup</a> • + <a href="/docs/try_local_system.md">Local Setup Guide (Hyperswitch App Server)</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> + <br> + <a href="#supported-features">Supported Features</a> • + <a href="#community">Community</a> • + <a href="#bugs-and-feature-requests">Bugs and feature requests</a> • + <a href="#versioning">Versioning</a> • + <a href="#FAQs">FAQs</a> • + <a href="#copyright-and-license">Copyright and License</a> </p> <p align="center"> @@ -53,8 +54,38 @@ Using Hyperswitch, you can: <br> <img src="./docs/imgs/hyperswitch-product.png" alt="Hyperswitch-Product" width="50%"/> -<a href="#Quick Start Guide"> - <h2 id="Quick Start Guide">⚡️ Quick Start Guide</h2> +<a href="https://app.hyperswitch.io/"> + <h2 id="try-a-payment">⚡️ Try a Payment</h2> +</a> + +To quickly experience the ease that Hyperswitch provides while handling the payment, you can signup on [hyperswitch-control-center][dashboard-link], and try a payment. + +Congratulations 🎉 on making your first payment with Hyperswitch. + +<a href="#Get Started with Hyperswitch"> + <h2 id="get-started-with-hyperswitch">Get Started with Hyperswitch</h2> +</a> + +### [For Enterprises][docs-link-for-enterprise] + Hyperswitch helps enterprises in - + - Improving profitability + - Increasing conversion rates + - Lowering payment costs + - Streamlining payment operations + + Hyperswitch has ample features for businesses of all domains and sizes. [**Check out our offerings**][website-link]. + +### [For Contributors][contributing-guidelines] + + Hyperswitch is an open-source project that aims to make digital payments accessible to people across the globe like a basic utility. With the vision of developing Hyperswitch as the **Linux of Payments**, we seek support from developers worldwide. + + Utilise the following resources to quickstart your journey with Hyperswitch - + - [Guide for contributors][contributing-guidelines] + - [Developer Docs][docs-link-for-developers] + - [Learning Resources][learning-resources] + +<a href="#Quick Setup"> + <h2 id="quick-setup">⚡️ Quick Setup</h2> </a> ### One-click deployment on AWS cloud @@ -85,11 +116,16 @@ This will start the app server, web client and control center. Check out the [local setup guide][local-setup-guide] for a more comprehensive setup, which includes the [scheduler and monitoring services][docker-compose-scheduler-monitoring]. +[docs-link-for-enterprise]: https://docs.hyperswitch.io/hyperswitch-cloud/quickstart +[docs-link-for-developers]: https://docs.hyperswitch.io/hyperswitch-open-source/overview +[contributing-guidelines]: docs/CONTRIBUTING.md +[dashboard-link]: https://app.hyperswitch.io/ +[website-link]: https://hyperswitch.io/ +[learning-resources]: https://docs.hyperswitch.io/learn-more/payment-flows [local-setup-guide]: /docs/try_local_system.md [docker-compose-scheduler-monitoring]: /docs/try_local_system.md#run-the-scheduler-and-monitoring-services - <a href="#Fast-Integration-for-Stripe-Users"> - <h2 id="Fast Integration for Stripe Users">🔌 Fast Integration for Stripe Users</h2> + <h2 id="fast-integration-for-stripe-users">🔌 Fast Integration for Stripe Users</h2> </a> If you are already using Stripe, integrating with Hyperswitch is fun, fast & easy. @@ -103,14 +139,14 @@ Try the steps below to get a feel for how quick the setup is: [migrate-from-stripe]: https://hyperswitch.io/docs/migrateFromStripe <a href="#Supported-Features"> - <h2 id="Supported Features">✅ Supported Features</h2> + <h2 id="supported-features">✅ Supported Features</h2> </a> ### 🌟 Supported Payment Processors and Methods -As of Sept 2023, we support 50+ payment processors and multiple global payment methods. +As of Aug 2024, Hyperswitch supports 50+ payment processors and multiple global payment methods. In addition, we are continuously integrating new processors based on their reach and community requests. -Our target is to support 100+ processors by H2 2023. +Our target is to support 100+ processors by H2 2024. You can find the latest list of payment processors, supported methods, and features [here][supported-connectors-and-features]. [supported-connectors-and-features]: https://hyperswitch.io/pm-list @@ -146,15 +182,6 @@ analytics, and operations end-to-end: You can [try the hosted version in our sandbox][dashboard]. -<a href="#FAQs"> - <h2 id="FAQs">🤔 FAQs</h2> -</a> - -Got more questions? -Please refer to our [FAQs page][faqs]. - -[faqs]: https://hyperswitch.io/docs/devSupport - <!-- ## Documentation @@ -167,58 +194,10 @@ Please refer to the following documentation pages: - Router Architecture [Link] --> -<a href="#what's-Included❓"> - <h2 id="what's-Included❓">What's Included❓</h2> -</a> - -Within the repositories, you'll find the following directories and files, -logically grouping common assets and providing both compiled and minified -variations. - -### Repositories - -The current setup contains a single repo, which contains the core payment router -and the various connector integrations under the `src/connector` sub-directory. - <!-- ### Sub-Crates --> -### 🌳 Files Tree Layout - -<!-- FIXME: this table should either be generated by a script or smoke test -should be introduced, checking it agrees with the actual structure --> - -```text -. -├── config : Initial startup config files for the router -├── connector-template : boilerplate code for connectors -├── crates : sub-crates -│ ├── api_models : Request/response models for the `router` crate -│ ├── cards : Types to handle card masking and validation -│ ├── common_enums : Enums shared across the request/response types and database types -│ ├── common_utils : Utilities shared across `router` and other crates -│ ├── 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, AWS KMS, etc. -│ ├── masking : Personal Identifiable Information protection -│ ├── redis_interface : A user-friendly interface to Redis -│ ├── router : Main crate of the project -│ ├── router_derive : Utility macros for the `router` crate -│ ├── router_env : Environment of payment router: logger, basic config, its environment awareness -│ ├── scheduler : Scheduling and executing deferred tasks like mail scheduling -│ ├── storage_impl : Storage backend implementations for data structures & objects -│ └── test_utils : Utilities to run Postman and connector UI tests -├── docs : hand-written documentation -├── loadtest : performance benchmarking setup -├── migrations : diesel DB setup -├── monitoring : Grafana & Loki monitoring related configuration files -├── openapi : automatically generated OpenAPI spec -├── postman : postman scenarios API -└── scripts : automation, testing, and other utility scripts -``` - <a href="#Join-us-in-building-Hyperswitch"> - <h2 id="Join-us-in-building-Hyperswitch">💪 Join us in building Hyperswitch</h2> + <h2 id="join-us-in-building-hyperswitch">💪 Join us in building Hyperswitch</h2> </a> ### 🤝 Our Belief @@ -272,7 +251,7 @@ development. For example, some of the code in core functions (e.g., `payments_core`) is written to be more readable than pure-idiomatic. <a href="#Community"> - <h2 id="Community">👥 Community</h2> + <h2 id="community">👥 Community</h2> </a> Get updates on Hyperswitch development and chat with the community: @@ -304,7 +283,7 @@ Get updates on Hyperswitch development and chat with the community: </div> <a href="#Bugs and feature requests"> - <h2 id="Bugs and feature requests">🐞 Bugs and feature requests</h2> + <h2 id="bugs-and-feature-requests">🐞 Bugs and feature requests</h2> </a> Please read the issue guidelines and search for [existing and closed issues]. @@ -314,13 +293,22 @@ If your problem or idea is not addressed yet, please [open a new issue]. [open a new issue]: https://github.com/juspay/hyperswitch/issues/new/choose <a href="#Versioning"> - <h2 id="Versioning">🔖 Versioning</h2> + <h2 id="versioning">🔖 Versioning</h2> </a> Check the [CHANGELOG.md](./CHANGELOG.md) file for details. +<a href="#FAQs"> + <h2 id="FAQs">🤔 FAQs</h2> +</a> + +Got more questions? +Please refer to our [FAQs page][faqs]. + +[faqs]: https://hyperswitch.io/docs/devSupport + <a href="#©Copyright and License"> - <h2 id="©Copyright and License">©️ Copyright and License</h2> + <h2 id="copyright-and-license">©️ Copyright and License</h2> </a> This product is licensed under the [Apache 2.0 License](LICENSE).
2024-07-03T08:42:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> to close #5344 ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
95e9c8523544bad4a034e61f62f6a321a8990963
juspay/hyperswitch
juspay__hyperswitch-5352
Bug: refactor: migrate user roles table to support v2 - Make org_id and merchant_id nullable. - Add new nullable columns profile_id, entity_id , entity_type, version
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 96678a7a3e1..f0059994cb6 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -19,7 +19,8 @@ pub mod diesel_exports { DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, - DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, + DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub use common_enums::*; @@ -298,3 +299,24 @@ pub enum TotpStatus { #[default] NotSet, } + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::EnumString, + strum::Display, +)] +#[diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum UserRoleVersion { + #[default] + V1, + V2, +} diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index b3fa3994793..2f2923db000 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -1,7 +1,10 @@ use common_utils::id_type; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; -use crate::{query::generics, schema::user_roles::dsl, user_role::*, PgPooledConn, StorageResult}; +use crate::{ + enums::UserRoleVersion, query::generics, schema::user_roles::dsl, user_role::*, PgPooledConn, + StorageResult, +}; impl UserRoleNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole> { @@ -10,10 +13,14 @@ impl UserRoleNew { } impl UserRole { - pub async fn find_by_user_id(conn: &PgPooledConn, user_id: String) -> StorageResult<Self> { + pub async fn find_by_user_id( + conn: &PgPooledConn, + user_id: String, + version: UserRoleVersion, + ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, - dsl::user_id.eq(user_id), + dsl::user_id.eq(user_id).and(dsl::version.eq(version)), ) .await } @@ -22,12 +29,14 @@ impl UserRole { conn: &PgPooledConn, user_id: String, merchant_id: id_type::MerchantId, + version: UserRoleVersion, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::user_id .eq(user_id) - .and(dsl::merchant_id.eq(merchant_id)), + .and(dsl::merchant_id.eq(merchant_id)) + .and(dsl::version.eq(version)), ) .await } @@ -37,6 +46,7 @@ impl UserRole { user_id: String, merchant_id: id_type::MerchantId, update: UserRoleUpdate, + version: UserRoleVersion, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, @@ -47,7 +57,8 @@ impl UserRole { conn, dsl::user_id .eq(user_id) - .and(dsl::merchant_id.eq(merchant_id)), + .and(dsl::merchant_id.eq(merchant_id)) + .and(dsl::version.eq(version)), UserRoleUpdateInternal::from(update), ) .await @@ -58,10 +69,14 @@ impl UserRole { user_id: String, org_id: id_type::OrganizationId, update: UserRoleUpdate, + version: UserRoleVersion, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, - dsl::user_id.eq(user_id).and(dsl::org_id.eq(org_id)), + dsl::user_id + .eq(user_id) + .and(dsl::org_id.eq(org_id)) + .and(dsl::version.eq(version)), UserRoleUpdateInternal::from(update), ) .await @@ -71,20 +86,26 @@ impl UserRole { conn: &PgPooledConn, user_id: String, merchant_id: id_type::MerchantId, + version: UserRoleVersion, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::user_id .eq(user_id) - .and(dsl::merchant_id.eq(merchant_id)), + .and(dsl::merchant_id.eq(merchant_id)) + .and(dsl::version.eq(version)), ) .await } - pub async fn list_by_user_id(conn: &PgPooledConn, user_id: String) -> StorageResult<Vec<Self>> { + pub async fn list_by_user_id( + conn: &PgPooledConn, + user_id: String, + version: UserRoleVersion, + ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, - dsl::user_id.eq(user_id), + dsl::user_id.eq(user_id).and(dsl::version.eq(version)), None, None, Some(dsl::created_at.asc()), @@ -95,10 +116,13 @@ impl UserRole { pub async fn list_by_merchant_id( conn: &PgPooledConn, merchant_id: id_type::MerchantId, + version: UserRoleVersion, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, - dsl::merchant_id.eq(merchant_id), + dsl::merchant_id + .eq(merchant_id) + .and(dsl::version.eq(version)), None, None, Some(dsl::created_at.asc()), diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 544a99bccb5..185677c4c75 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1243,16 +1243,16 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - user_roles (user_id, merchant_id) { + user_roles (id) { id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 64] - merchant_id -> Varchar, + merchant_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Varchar, #[max_length = 64] - org_id -> Varchar, + org_id -> Nullable<Varchar>, status -> UserStatus, #[max_length = 64] created_by -> Varchar, @@ -1260,6 +1260,13 @@ diesel::table! { last_modified_by -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + entity_id -> Nullable<Varchar>, + #[max_length = 64] + entity_type -> Nullable<Varchar>, + version -> UserRoleVersion, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index e60e2da0a47..28937b48db4 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1252,16 +1252,16 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - user_roles (user_id, merchant_id) { + user_roles (id) { id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 64] - merchant_id -> Varchar, + merchant_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Varchar, #[max_length = 64] - org_id -> Varchar, + org_id -> Nullable<Varchar>, status -> UserStatus, #[max_length = 64] created_by -> Varchar, @@ -1269,6 +1269,13 @@ diesel::table! { last_modified_by -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + entity_id -> Nullable<Varchar>, + #[max_length = 64] + entity_type -> Nullable<Varchar>, + version -> UserRoleVersion, } } diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs index 7f7c8484e8f..d484db2c6ba 100644 --- a/crates/diesel_models/src/user_role.rs +++ b/crates/diesel_models/src/user_role.rs @@ -9,28 +9,36 @@ use crate::{enums, schema::user_roles}; pub struct UserRole { pub id: i32, pub user_id: String, - pub merchant_id: id_type::MerchantId, + pub merchant_id: Option<id_type::MerchantId>, pub role_id: String, - pub org_id: id_type::OrganizationId, + pub org_id: Option<id_type::OrganizationId>, pub status: enums::UserStatus, pub created_by: String, pub last_modified_by: String, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, + pub profile_id: Option<String>, + pub entity_id: Option<String>, + pub entity_type: Option<String>, + pub version: enums::UserRoleVersion, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = user_roles)] pub struct UserRoleNew { pub user_id: String, - pub merchant_id: id_type::MerchantId, + pub merchant_id: Option<id_type::MerchantId>, pub role_id: String, - pub org_id: id_type::OrganizationId, + pub org_id: Option<id_type::OrganizationId>, pub status: enums::UserStatus, pub created_by: String, pub last_modified_by: String, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, + pub profile_id: Option<String>, + pub entity_id: Option<String>, + pub entity_type: Option<String>, + pub version: enums::UserRoleVersion, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 9389240c972..ba85a382dbf 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -8,7 +8,7 @@ use common_utils::types::keymanager::Identifier; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; use diesel_models::{ - enums::{TotpStatus, UserStatus}, + enums::{TotpStatus, UserRoleVersion, UserStatus}, user as storage_user, user_authentication_method::{UserAuthenticationMethodNew, UserAuthenticationMethodUpdate}, user_role::UserRoleNew, @@ -81,11 +81,16 @@ pub async fn signup_with_merchant_id( ) .await; + let Some(merchant_id) = user_role.merchant_id else { + return Err(report!(UserErrors::InternalServerError) + .attach_printable("merchant_id not found for user_role")); + }; + logger::info!(?send_email_result); Ok(ApplicationResponse::Json(user_api::AuthorizeResponse { is_email_sent: send_email_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), - merchant_id: user_role.merchant_id, + merchant_id, })) } @@ -203,7 +208,7 @@ pub async fn signin( .attach_printable("User role with preferred_merchant_id not found")?; domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy { user: user_from_db, - user_role: preferred_role, + user_role: Box::new(preferred_role), }) } else { let user_roles = user_from_db.get_roles_from_db(&state).await?; @@ -272,13 +277,17 @@ pub async fn connect_account( ) .await; + let Some(merchant_id) = user_role.merchant_id else { + return Err(report!(UserErrors::InternalServerError) + .attach_printable("merchant_id not found for user_role")); + }; logger::info!(?send_email_result); return Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: send_email_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), - merchant_id: user_role.merchant_id, + merchant_id, }, )); } else if find_user @@ -323,13 +332,18 @@ pub async fn connect_account( ) .await; + let Some(merchant_id) = user_role.merchant_id else { + return Err(report!(UserErrors::InternalServerError) + .attach_printable("merchant_id not found for user_role")); + }; + logger::info!(?send_email_result); return Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: send_email_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), - merchant_id: user_role.merchant_id, + merchant_id, }, )); } else { @@ -587,6 +601,7 @@ pub async fn reset_password( status: UserStatus::Active, modified_by: user.user_id.clone(), }, + UserRoleVersion::V1, ) .await; logger::info!(?update_status_result); @@ -719,9 +734,9 @@ async fn handle_existing_user_invitation( .store .insert_user_role(UserRoleNew { user_id: invitee_user_from_db.get_user_id().to_owned(), - merchant_id: user_from_token.merchant_id.clone(), + merchant_id: Some(user_from_token.merchant_id.clone()), role_id: request.role_id.clone(), - org_id: user_from_token.org_id.clone(), + org_id: Some(user_from_token.org_id.clone()), status: { if cfg!(feature = "email") { UserStatus::InvitationSent @@ -733,6 +748,10 @@ async fn handle_existing_user_invitation( last_modified_by: user_from_token.user_id.clone(), created_at: now, last_modified: now, + profile_id: None, + entity_id: None, + entity_type: None, + version: UserRoleVersion::V1, }) .await .map_err(|e| { @@ -807,14 +826,18 @@ async fn handle_new_user_invitation( .store .insert_user_role(UserRoleNew { user_id: new_user.get_user_id().to_owned(), - merchant_id: user_from_token.merchant_id.clone(), + merchant_id: Some(user_from_token.merchant_id.clone()), role_id: request.role_id.clone(), - org_id: user_from_token.org_id.clone(), + org_id: Some(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, + profile_id: None, + entity_id: None, + entity_type: None, + version: UserRoleVersion::V1, }) .await .map_err(|e| { @@ -916,7 +939,11 @@ pub async fn resend_invite( .into(); let user_role = state .store - .find_user_role_by_user_id_merchant_id(user.get_user_id(), &user_from_token.merchant_id) + .find_user_role_by_user_id_merchant_id( + user.get_user_id(), + &user_from_token.merchant_id, + UserRoleVersion::V1, + ) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -993,6 +1020,7 @@ pub async fn accept_invite_from_email( status: UserStatus::Active, modified_by: user.get_user_id().to_string(), }, + UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError)?; @@ -1065,6 +1093,7 @@ pub async fn accept_invite_from_email_token_only_flow( status: UserStatus::Active, modified_by: user_from_db.get_user_id().to_string(), }, + UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError)?; @@ -1241,7 +1270,7 @@ pub async fn switch_merchant_id( } else { let user_roles = state .store - .list_user_roles_by_user_id(&user_from_token.user_id) + .list_user_roles_by_user_id(&user_from_token.user_id, UserRoleVersion::V1) .await .change_context(UserErrors::InternalServerError)?; @@ -1252,7 +1281,17 @@ pub async fn switch_merchant_id( let user_role = active_user_roles .iter() - .find(|role| role.merchant_id == request.merchant_id) + .find_map(|role| { + let Some(ref merchant_id) = role.merchant_id else { + return Some(Err(report!(UserErrors::InternalServerError))); + }; + if merchant_id == &request.merchant_id { + Some(Ok(role)) + } else { + None + } + }) + .transpose()? .ok_or(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User doesn't have access to switch")?; @@ -1312,7 +1351,7 @@ pub async fn list_merchants_for_user( ) -> UserResponse<Vec<user_api::UserMerchantAccount>> { let user_roles = state .store - .list_user_roles_by_user_id(user_from_token.user_id.as_str()) + .list_user_roles_by_user_id(user_from_token.user_id.as_str(), UserRoleVersion::V1) .await .change_context(UserErrors::InternalServerError)?; @@ -1322,8 +1361,12 @@ pub async fn list_merchants_for_user( &(&state).into(), user_roles .iter() - .map(|role| role.merchant_id.clone()) - .collect(), + .map(|role| { + role.merchant_id + .clone() + .ok_or(UserErrors::InternalServerError) + }) + .collect::<Result<Vec<_>, _>>()?, ) .await .change_context(UserErrors::InternalServerError)?; @@ -1355,6 +1398,7 @@ pub async fn get_user_details_in_merchant_account( .find_user_role_by_user_id_merchant_id( required_user.get_user_id(), &user_from_token.merchant_id, + UserRoleVersion::V1, ) .await .to_not_found_response(UserErrors::InvalidRoleOperation) @@ -1390,7 +1434,7 @@ pub async fn list_users_for_merchant_account( ) -> UserResponse<user_api::ListUsersResponse> { let user_roles: HashMap<String, _> = state .store - .list_user_roles_by_merchant_id(&user_from_token.merchant_id) + .list_user_roles_by_merchant_id(&user_from_token.merchant_id, UserRoleVersion::V1) .await .change_context(UserErrors::InternalServerError) .attach_printable("No user roles for given merchant id")? @@ -1422,8 +1466,14 @@ pub async fn list_users_for_merchant_account( roles::RoleInfo::from_role_id( &state, &user_role.role_id.clone(), - &user_role.merchant_id, - &user_role.org_id, + user_role + .merchant_id + .as_ref() + .ok_or(UserErrors::InternalServerError)?, + user_role + .org_id + .as_ref() + .ok_or(UserErrors::InternalServerError)?, ) .await .map(|role_info| (user, user_role, role_info)) @@ -1491,7 +1541,7 @@ pub async fn verify_email( .attach_printable("User role with preferred_merchant_id not found")?; domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy { user: user_from_db, - user_role: preferred_role, + user_role: Box::new(preferred_role), }) } else { let user_roles = user_from_db.get_roles_from_db(&state).await?; @@ -1624,10 +1674,11 @@ pub async fn verify_token( })?; let merchant_id = state .store - .find_user_role_by_user_id(&req.user_id) + .find_user_role_by_user_id(&req.user_id, UserRoleVersion::V1) .await .change_context(UserErrors::InternalServerError)? - .merchant_id; + .merchant_id + .ok_or(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json(user_api::VerifyTokenResponse { merchant_id: merchant_id.to_owned(), @@ -1653,7 +1704,11 @@ pub async fn update_user_details( 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) + .find_user_role_by_user_id_merchant_id( + user.get_user_id(), + preferred_merchant_id, + UserRoleVersion::V1, + ) .await .map_err(|e| { if e.current_context().is_db_not_found() { diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 5d93c00909d..a728836857c 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,5 +1,8 @@ use api_models::{user as user_api, user_role as user_role_api}; -use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate}; +use diesel_models::{ + enums::{UserRoleVersion, UserStatus}, + user_role::UserRoleUpdate, +}; use error_stack::{report, ResultExt}; use router_env::logger; @@ -101,11 +104,15 @@ pub async fn update_user_role( .store .update_user_role_by_user_id_merchant_id( user_to_be_updated.get_user_id(), - &user_role_to_be_updated.merchant_id, + &user_role_to_be_updated + .merchant_id + .ok_or(UserErrors::InternalServerError) + .attach_printable("merchant_id not found in user_role")?, UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id, }, + UserRoleVersion::V1, ) .await .to_not_found_response(UserErrors::InvalidRoleOperation) @@ -146,6 +153,7 @@ pub async fn transfer_org_ownership( &user_from_token.user_id, user_to_be_updated.get_user_id(), &user_from_token.org_id, + UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError)?; @@ -183,6 +191,7 @@ pub async fn accept_invitation( status: UserStatus::Active, modified_by: user_token.user_id.clone(), }, + UserRoleVersion::V1, ) .await .map_err(|e| { @@ -213,6 +222,7 @@ pub async fn merchant_select( status: UserStatus::Active, modified_by: user_token.user_id.clone(), }, + UserRoleVersion::V1, ) .await .map_err(|e| { @@ -267,6 +277,7 @@ pub async fn merchant_select_token_only_flow( status: UserStatus::Active, modified_by: user_token.user_id.clone(), }, + UserRoleVersion::V1, ) .await .map_err(|e| { @@ -329,15 +340,17 @@ pub async fn delete_user_role( let user_roles = state .store - .list_user_roles_by_user_id(user_from_db.get_user_id()) + .list_user_roles_by_user_id(user_from_db.get_user_id(), UserRoleVersion::V1) .await .change_context(UserErrors::InternalServerError)?; - match user_roles - .iter() - .find(|&role| role.merchant_id == user_from_token.merchant_id) - { - Some(user_role) => { + for user_role in user_roles.iter() { + let Some(merchant_id) = user_role.merchant_id.as_ref() else { + return Err(report!(UserErrors::InternalServerError)) + .attach_printable("merchant_id not found for user_role"); + }; + + if merchant_id == &user_from_token.merchant_id { let role_info = roles::RoleInfo::from_role_id( &state, &user_role.role_id, @@ -350,12 +363,11 @@ pub async fn delete_user_role( return Err(report!(UserErrors::InvalidDeleteOperation)) .attach_printable(format!("role_id = {} is not deletable", user_role.role_id)); } - } - None => { + } else { return Err(report!(UserErrors::InvalidDeleteOperation)) .attach_printable("User is not associated with the merchant"); } - }; + } let deleted_user_role = if user_roles.len() > 1 { state @@ -363,6 +375,7 @@ pub async fn delete_user_role( .delete_user_role_by_user_id_merchant_id( user_from_db.get_user_id(), &user_from_token.merchant_id, + UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError) @@ -380,6 +393,7 @@ pub async fn delete_user_role( .delete_user_role_by_user_id_merchant_id( user_from_db.get_user_id(), &user_from_token.merchant_id, + UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError) diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 003f3ff4845..55fb7096a3a 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2535,17 +2535,21 @@ impl UserRoleInterface for KafkaStore { async fn find_user_role_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> CustomResult<user_storage::UserRole, errors::StorageError> { - self.diesel_store.find_user_role_by_user_id(user_id).await + self.diesel_store + .find_user_role_by_user_id(user_id, version) + .await } async fn find_user_role_by_user_id_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store - .find_user_role_by_user_id_merchant_id(user_id, merchant_id) + .find_user_role_by_user_id_merchant_id(user_id, merchant_id, version) .await } @@ -2554,9 +2558,10 @@ impl UserRoleInterface for KafkaStore { user_id: &str, merchant_id: &id_type::MerchantId, update: user_storage::UserRoleUpdate, + version: enums::UserRoleVersion, ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store - .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update) + .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update, version) .await } @@ -2565,9 +2570,10 @@ impl UserRoleInterface for KafkaStore { user_id: &str, org_id: &id_type::OrganizationId, update: user_storage::UserRoleUpdate, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { self.diesel_store - .update_user_roles_by_user_id_org_id(user_id, org_id, update) + .update_user_roles_by_user_id_org_id(user_id, org_id, update, version) .await } @@ -2575,17 +2581,21 @@ impl UserRoleInterface for KafkaStore { &self, user_id: &str, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store - .delete_user_role_by_user_id_merchant_id(user_id, merchant_id) + .delete_user_role_by_user_id_merchant_id(user_id, merchant_id, version) .await } async fn list_user_roles_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { - self.diesel_store.list_user_roles_by_user_id(user_id).await + self.diesel_store + .list_user_roles_by_user_id(user_id, version) + .await } async fn transfer_org_ownership_between_users( @@ -2593,18 +2603,20 @@ impl UserRoleInterface for KafkaStore { from_user_id: &str, to_user_id: &str, org_id: &id_type::OrganizationId, + version: enums::UserRoleVersion, ) -> CustomResult<(), errors::StorageError> { self.diesel_store - .transfer_org_ownership_between_users(from_user_id, to_user_id, org_id) + .transfer_org_ownership_between_users(from_user_id, to_user_id, org_id, version) .await } async fn list_user_roles_by_merchant_id( &self, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { self.diesel_store - .list_user_roles_by_merchant_id(merchant_id) + .list_user_roles_by_merchant_id(merchant_id, version) .await } } diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index 7f16cedd570..cc3e2460967 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -1,4 +1,4 @@ -use std::{collections::HashSet, ops::Not}; +use std::collections::HashSet; use async_bb8_diesel::AsyncConnection; use common_utils::id_type; @@ -23,12 +23,14 @@ pub trait UserRoleInterface { async fn find_user_role_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn find_user_role_by_user_id_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn update_user_role_by_user_id_merchant_id( @@ -36,6 +38,7 @@ pub trait UserRoleInterface { user_id: &str, merchant_id: &id_type::MerchantId, update: storage::UserRoleUpdate, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn update_user_roles_by_user_id_org_id( @@ -43,22 +46,26 @@ pub trait UserRoleInterface { user_id: &str, org_id: &id_type::OrganizationId, update: storage::UserRoleUpdate, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn list_user_roles_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn list_user_roles_by_merchant_id( &self, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn transfer_org_ownership_between_users( @@ -66,6 +73,7 @@ pub trait UserRoleInterface { from_user_id: &str, to_user_id: &str, org_id: &id_type::OrganizationId, + version: enums::UserRoleVersion, ) -> CustomResult<(), errors::StorageError>; } @@ -87,9 +95,10 @@ impl UserRoleInterface for Store { async fn find_user_role_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::find_by_user_id(&conn, user_id.to_owned()) + storage::UserRole::find_by_user_id(&conn, user_id.to_owned(), version) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -99,12 +108,14 @@ impl UserRoleInterface for Store { &self, user_id: &str, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> 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(), + version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -116,6 +127,7 @@ impl UserRoleInterface for Store { user_id: &str, merchant_id: &id_type::MerchantId, update: storage::UserRoleUpdate, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserRole::update_by_user_id_merchant_id( @@ -123,6 +135,7 @@ impl UserRoleInterface for Store { user_id.to_owned(), merchant_id.to_owned(), update, + version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -134,6 +147,7 @@ impl UserRoleInterface for Store { user_id: &str, org_id: &id_type::OrganizationId, update: storage::UserRoleUpdate, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserRole::update_by_user_id_org_id( @@ -141,6 +155,7 @@ impl UserRoleInterface for Store { user_id.to_owned(), org_id.to_owned(), update, + version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -151,6 +166,7 @@ impl UserRoleInterface for Store { &self, user_id: &str, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; @@ -158,6 +174,7 @@ impl UserRoleInterface for Store { &conn, user_id.to_owned(), merchant_id.to_owned(), + version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -167,9 +184,10 @@ impl UserRoleInterface for Store { async fn list_user_roles_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::list_by_user_id(&conn, user_id.to_owned()) + storage::UserRole::list_by_user_id(&conn, user_id.to_owned(), version) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -178,9 +196,10 @@ impl UserRoleInterface for Store { async fn list_user_roles_by_merchant_id( &self, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::list_by_merchant_id(&conn, merchant_id.to_owned()) + storage::UserRole::list_by_merchant_id(&conn, merchant_id.to_owned(), version) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -191,6 +210,7 @@ impl UserRoleInterface for Store { from_user_id: &str, to_user_id: &str, org_id: &id_type::OrganizationId, + version: enums::UserRoleVersion, ) -> CustomResult<(), errors::StorageError> { let conn = connection::pg_connection_write(self) .await @@ -205,6 +225,7 @@ impl UserRoleInterface for Store { role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), modified_by: from_user_id.to_owned(), }, + version, ) .await .map_err(|e| *e.current_context())?; @@ -217,43 +238,56 @@ impl UserRoleInterface for Store { role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), modified_by: from_user_id.to_owned(), }, + version, ) .await .map_err(|e| *e.current_context())?; let new_org_admin_merchant_ids = new_org_admin_user_roles .iter() - .map(|user_role| user_role.merchant_id.to_owned()) - .collect::<HashSet<_>>(); + .map(|user_role| { + user_role + .merchant_id + .to_owned() + .ok_or(errors::DatabaseError::Others) + }) + .collect::<Result<HashSet<_>, _>>()?; let now = common_utils::date_time::now(); - let missing_new_user_roles = - old_org_admin_user_roles.into_iter().filter_map(|old_role| { - new_org_admin_merchant_ids - .contains(&old_role.merchant_id) - .not() - .then_some({ - storage::UserRoleNew { - user_id: to_user_id.to_string(), - merchant_id: old_role.merchant_id, - role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), - org_id: org_id.to_owned(), - status: enums::UserStatus::Active, - created_by: from_user_id.to_string(), - last_modified_by: from_user_id.to_string(), - created_at: now, - last_modified: now, - } - }) - }); - - futures::future::try_join_all(missing_new_user_roles.map(|user_role| async { - user_role - .insert(&conn) - .await - .map_err(|e| *e.current_context()) - })) + let mut missing_new_user_roles = Vec::new(); + + for old_role in old_org_admin_user_roles { + let Some(old_role_merchant_id) = &old_role.merchant_id else { + return Err(errors::DatabaseError::Others); + }; + if !new_org_admin_merchant_ids.contains(old_role_merchant_id) { + missing_new_user_roles.push(storage::UserRoleNew { + user_id: to_user_id.to_string(), + merchant_id: Some(old_role_merchant_id.to_owned()), + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + org_id: Some(org_id.to_owned()), + status: enums::UserStatus::Active, + created_by: from_user_id.to_string(), + last_modified_by: from_user_id.to_string(), + created_at: now, + last_modified: now, + profile_id: None, + entity_id: None, + entity_type: None, + version: enums::UserRoleVersion::V1, + }); + } + } + + futures::future::try_join_all(missing_new_user_roles.into_iter().map( + |user_role| async { + user_role + .insert(&conn) + .await + .map_err(|e| *e.current_context()) + }, + )) .await?; Ok::<_, errors::DatabaseError>(()) @@ -293,6 +327,10 @@ impl UserRoleInterface for MockDb { last_modified: user_role.last_modified, last_modified_by: user_role.last_modified_by, org_id: user_role.org_id, + profile_id: None, + entity_id: None, + entity_type: None, + version: enums::UserRoleVersion::V1, }; user_roles.push(user_role.clone()); Ok(user_role) @@ -301,11 +339,12 @@ impl UserRoleInterface for MockDb { async fn find_user_role_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> 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) + .find(|user_role| user_role.user_id == user_id && user_role.version == version) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( @@ -319,18 +358,31 @@ impl UserRoleInterface for MockDb { &self, user_id: &str, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> 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(), - ) + + for user_role in user_roles.iter() { + let Some(user_role_merchant_id) = &user_role.merchant_id else { + return Err(errors::StorageError::DatabaseError( + report!(errors::DatabaseError::Others) + .attach_printable("merchant_id not found for user_role"), + ) + .into()); + }; + if user_role.user_id == user_id + && user_role_merchant_id == merchant_id + && user_role.version == version + { + return Ok(user_role.clone()); + } + } + + Err(errors::StorageError::ValueNotFound(format!( + "No user role available for user_id = {} and merchant_id = {}", + user_id, merchant_id + )) + .into()) } async fn update_user_role_by_user_id_merchant_id( @@ -338,38 +390,46 @@ impl UserRoleInterface for MockDb { user_id: &str, merchant_id: &id_type::MerchantId, update: storage::UserRoleUpdate, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; - user_roles - .iter_mut() - .find(|user_role| user_role.user_id == user_id && user_role.merchant_id == *merchant_id) - .map(|user_role| { - *user_role = match &update { + + for user_role in user_roles.iter_mut() { + let Some(user_role_merchant_id) = &user_role.merchant_id else { + return Err(errors::StorageError::DatabaseError( + report!(errors::DatabaseError::Others) + .attach_printable("merchant_id not found for user_role"), + ) + .into()); + }; + if user_role.user_id == user_id + && user_role_merchant_id == merchant_id + && user_role.version == version + { + match &update { storage::UserRoleUpdate::UpdateRole { role_id, modified_by, - } => storage::UserRole { - role_id: role_id.to_string(), - last_modified_by: modified_by.to_string(), - ..user_role.to_owned() - }, + } => { + user_role.role_id = role_id.to_string(); + user_role.last_modified_by = modified_by.to_string(); + } storage::UserRoleUpdate::UpdateStatus { status, modified_by, - } => storage::UserRole { - status: status.to_owned(), - last_modified_by: modified_by.to_owned(), - ..user_role.to_owned() - }, + } => { + user_role.status = *status; + user_role.last_modified_by = modified_by.to_string(); + } }; - user_role.to_owned() - }) - .ok_or( - errors::StorageError::ValueNotFound(format!( - "No user role available for user_id = {user_id} and merchant_id = {merchant_id:?}" - )) - .into(), - ) + return Ok(user_role.clone()); + } + } + + Err(errors::StorageError::ValueNotFound(format!( + "No user role available for user_id = {user_id} and merchant_id = {merchant_id:?}" + )) + .into()) } async fn update_user_roles_by_user_id_org_id( @@ -377,11 +437,22 @@ impl UserRoleInterface for MockDb { user_id: &str, org_id: &id_type::OrganizationId, update: storage::UserRoleUpdate, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; let mut updated_user_roles = Vec::new(); for user_role in user_roles.iter_mut() { - if user_role.user_id == user_id && user_role.org_id == *org_id { + let Some(user_role_org_id) = &user_role.org_id else { + return Err(errors::StorageError::DatabaseError( + report!(errors::DatabaseError::Others) + .attach_printable("org_id not found for user_role"), + ) + .into()); + }; + if user_role.user_id == user_id + && user_role_org_id == org_id + && user_role.version == version + { match &update { storage::UserRoleUpdate::UpdateRole { role_id, @@ -416,6 +487,7 @@ impl UserRoleInterface for MockDb { from_user_id: &str, to_user_id: &str, org_id: &id_type::OrganizationId, + version: enums::UserRoleVersion, ) -> CustomResult<(), errors::StorageError> { let old_org_admin_user_roles = self .update_user_roles_by_user_id_org_id( @@ -425,6 +497,7 @@ impl UserRoleInterface for MockDb { role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), modified_by: from_user_id.to_string(), }, + version, ) .await?; @@ -436,35 +509,53 @@ impl UserRoleInterface for MockDb { role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), modified_by: from_user_id.to_string(), }, + version, ) .await?; let new_org_admin_merchant_ids = new_org_admin_user_roles .iter() - .map(|user_role| user_role.merchant_id.to_owned()) - .collect::<HashSet<_>>(); + .map(|user_role| { + user_role.merchant_id.to_owned().ok_or(report!( + errors::StorageError::DatabaseError( + report!(errors::DatabaseError::Others) + .attach_printable("merchant_id not found for user_role"), + ) + )) + }) + .collect::<Result<HashSet<_>, _>>()?; let now = common_utils::date_time::now(); + let mut missing_new_user_roles = Vec::new(); + + for old_roles in old_org_admin_user_roles { + let Some(merchant_id) = &old_roles.merchant_id else { + return Err(errors::StorageError::DatabaseError( + report!(errors::DatabaseError::Others) + .attach_printable("merchant id not found for user role"), + ) + .into()); + }; + if !new_org_admin_merchant_ids.contains(merchant_id) { + let new_user_role = storage::UserRoleNew { + user_id: to_user_id.to_string(), + merchant_id: Some(merchant_id.to_owned()), + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + org_id: Some(org_id.to_owned()), + status: enums::UserStatus::Active, + created_by: from_user_id.to_string(), + last_modified_by: from_user_id.to_string(), + created_at: now, + last_modified: now, + profile_id: None, + entity_id: None, + entity_type: None, + version: enums::UserRoleVersion::V1, + }; - let missing_new_user_roles = old_org_admin_user_roles - .into_iter() - .filter_map(|old_roles| { - if !new_org_admin_merchant_ids.contains(&old_roles.merchant_id) { - Some(storage::UserRoleNew { - user_id: to_user_id.to_string(), - merchant_id: old_roles.merchant_id, - role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), - org_id: org_id.to_owned(), - status: enums::UserStatus::Active, - created_by: from_user_id.to_string(), - last_modified_by: from_user_id.to_string(), - created_at: now, - last_modified: now, - }) - } else { - None - } - }); + missing_new_user_roles.push(new_user_role); + } + } for user_role in missing_new_user_roles { self.insert_user_role(user_role).await?; @@ -477,14 +568,21 @@ impl UserRoleInterface for MockDb { &self, user_id: &str, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; - match user_roles - .iter() - .position(|role| role.user_id == user_id && role.merchant_id == *merchant_id) - { - Some(index) => Ok(user_roles.remove(index)), + let index = user_roles.iter().position(|role| { + role.user_id == user_id + && role.version == version + && match role.merchant_id { + Some(ref mid) => mid == merchant_id, + None => false, + } + }); + + match index { + Some(idx) => Ok(user_roles.remove(idx)), None => Err(errors::StorageError::ValueNotFound( "Cannot find user role to delete".to_string(), ) @@ -495,6 +593,7 @@ impl UserRoleInterface for MockDb { async fn list_user_roles_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; @@ -502,7 +601,7 @@ impl UserRoleInterface for MockDb { .iter() .cloned() .filter_map(|ele| { - if ele.user_id == user_id { + if ele.user_id == user_id && ele.version == version { return Some(ele); } None @@ -513,19 +612,26 @@ impl UserRoleInterface for MockDb { async fn list_user_roles_by_merchant_id( &self, merchant_id: &id_type::MerchantId, + version: enums::UserRoleVersion, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; - Ok(user_roles + let filtered_roles: Vec<_> = user_roles .iter() - .cloned() - .filter_map(|ele| { - if ele.merchant_id == *merchant_id { - return Some(ele); + .filter_map(|role| { + if let Some(role_merchant_id) = &role.merchant_id { + if role_merchant_id == merchant_id && role.version == version { + Some(role.clone()) + } else { + None + } + } else { + None } - None }) - .collect()) + .collect(); + + Ok(filtered_roles) } } @@ -551,8 +657,11 @@ impl UserRoleInterface for super::KafkaStore { async fn find_user_role_by_user_id( &self, user_id: &str, + version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { - self.diesel_store.find_user_role_by_user_id(user_id).await + self.diesel_store + .find_user_role_by_user_id(user_id, version) + .await } async fn delete_user_role_by_user_id_merchant_id( &self, diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs index be489a8ea06..910e2e8f96b 100644 --- a/crates/router/src/routes/recon.rs +++ b/crates/router/src/routes/recon.rs @@ -1,5 +1,6 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::recon as recon_api; +use diesel_models::enums::UserRoleVersion; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use router_env::Flow; @@ -81,10 +82,11 @@ pub async fn send_recon_request( .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let merchant_id = db - .find_user_role_by_user_id(&user.user_id) + .find_user_role_by_user_id(&user.user_id, UserRoleVersion::V1) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)? - .merchant_id; + .merchant_id + .ok_or(errors::ApiErrorResponse::InternalServerError)?; let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 95349cb4393..8b973a8cf44 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -9,9 +9,8 @@ use common_utils::{ types::keymanager::Identifier, }; use diesel_models::{ - enums::{TotpStatus, UserStatus}, - organization as diesel_org, - organization::Organization, + enums::{TotpStatus, UserRoleVersion, UserStatus}, + organization::{self as diesel_org, Organization}, user as storage_user, user_role::{UserRole, UserRoleNew}, }; @@ -655,7 +654,7 @@ impl NewUser { state .store .insert_user_role(UserRoleNew { - merchant_id: self.get_new_merchant().get_merchant_id(), + merchant_id: Some(self.get_new_merchant().get_merchant_id()), status: user_status, created_by: user_id.clone(), last_modified_by: user_id.clone(), @@ -663,10 +662,15 @@ impl NewUser { role_id, created_at: now, last_modified: now, - org_id: self - .get_new_merchant() - .get_new_organization() - .get_organization_id(), + org_id: Some( + self.get_new_merchant() + .get_new_organization() + .get_organization_id(), + ), + profile_id: None, + entity_id: None, + entity_type: None, + version: UserRoleVersion::V1, }) .await .change_context(UserErrors::InternalServerError) @@ -860,7 +864,7 @@ impl UserFromStorage { pub async fn get_role_from_db(&self, state: SessionState) -> UserResult<UserRole> { state .store - .find_user_role_by_user_id(&self.0.user_id) + .find_user_role_by_user_id(&self.0.user_id, UserRoleVersion::V1) .await .change_context(UserErrors::InternalServerError) } @@ -868,7 +872,7 @@ impl UserFromStorage { pub async fn get_roles_from_db(&self, state: &SessionState) -> UserResult<Vec<UserRole>> { state .store - .list_user_roles_by_user_id(&self.0.user_id) + .list_user_roles_by_user_id(&self.0.user_id, UserRoleVersion::V1) .await .change_context(UserErrors::InternalServerError) } @@ -931,7 +935,11 @@ impl UserFromStorage { ) -> CustomResult<UserRole, errors::StorageError> { state .store - .find_user_role_by_user_id_merchant_id(self.get_user_id(), merchant_id) + .find_user_role_by_user_id_merchant_id( + self.get_user_id(), + merchant_id, + UserRoleVersion::V1, + ) .await } @@ -945,7 +953,7 @@ impl UserFromStorage { } else { state .store - .list_user_roles_by_user_id(&self.0.user_id) + .list_user_roles_by_user_id(&self.0.user_id, UserRoleVersion::V1) .await? .into_iter() .find(|role| role.status == UserStatus::Active) @@ -1109,7 +1117,7 @@ impl SignInWithRoleStrategyType { { Ok(Self::SingleRole(SignInWithSingleRoleStrategy { user, - user_role: user_role.clone(), + user_role: Box::new(user_role.clone()), })) } else { Ok(Self::MultipleRoles(SignInWithMultipleRolesStrategy { @@ -1132,7 +1140,7 @@ impl SignInWithRoleStrategyType { pub struct SignInWithSingleRoleStrategy { pub user: UserFromStorage, - pub user_role: UserRole, + pub user_role: Box<UserRole>, } impl SignInWithSingleRoleStrategy { @@ -1145,7 +1153,7 @@ impl SignInWithSingleRoleStrategy { utils::user_role::set_role_permissions_in_cache_by_user_role(state, &self.user_role).await; let dashboard_entry_response = - utils::user::get_dashboard_entry_response(state, self.user, self.user_role, token)?; + utils::user::get_dashboard_entry_response(state, self.user, *self.user_role, token)?; Ok(user_api::SignInResponse::DashboardEntry( dashboard_entry_response, @@ -1169,8 +1177,12 @@ impl SignInWithMultipleRolesStrategy { &state.into(), self.user_roles .iter() - .map(|role| role.merchant_id.clone()) - .collect(), + .map(|role| { + role.merchant_id + .clone() + .ok_or(UserErrors::InternalServerError) + }) + .collect::<Result<Vec<_>, _>>()?, ) .await .change_context(UserErrors::InternalServerError)?; diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 97fb69074a6..cffdd05448a 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,5 +1,6 @@ use common_enums::TokenPurpose; use diesel_models::{enums::UserStatus, user_role::UserRole}; +use error_stack::report; use masking::Secret; use super::UserFromStorage; @@ -108,10 +109,16 @@ impl JWTFlow { ) -> UserResult<Secret<String>> { auth::AuthToken::new_token( next_flow.user.get_user_id().to_string(), - user_role.merchant_id.clone(), + user_role + .merchant_id + .clone() + .ok_or(report!(UserErrors::InternalServerError))?, user_role.role_id.clone(), &state.conf, - user_role.org_id.clone(), + user_role + .org_id + .clone() + .ok_or(report!(UserErrors::InternalServerError))?, ) .await .map(|token| token.into()) diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 58215bf1bce..72d2b83c6b4 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -6,7 +6,7 @@ use common_utils::{ encryption::Encryption, errors::CustomResult, id_type, types::keymanager::Identifier, }; use diesel_models::{enums::UserStatus, user_role::UserRole}; -use error_stack::ResultExt; +use error_stack::{report, ResultExt}; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; @@ -88,10 +88,20 @@ pub async fn generate_jwt_auth_token( ) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user.get_user_id().to_string(), - user_role.merchant_id.clone(), + user_role + .merchant_id + .as_ref() + .ok_or(report!(UserErrors::InternalServerError)) + .attach_printable("merchant_id not found for user_role")? + .clone(), user_role.role_id.clone(), &state.conf, - user_role.org_id.clone(), + user_role + .org_id + .as_ref() + .ok_or(report!(UserErrors::InternalServerError)) + .attach_printable("org_id not found for user_role")? + .clone(), ) .await?; Ok(Secret::new(token)) @@ -124,7 +134,10 @@ pub fn get_dashboard_entry_response( let verification_days_left = get_verification_days_left(state, &user)?; Ok(user_api::DashboardEntryResponse { - merchant_id: user_role.merchant_id, + merchant_id: user_role.merchant_id.ok_or( + report!(UserErrors::InternalServerError) + .attach_printable("merchant_id not found for user_role"), + )?, token, name: user.get_name(), email: user.get_email(), @@ -163,8 +176,16 @@ pub fn get_multiple_merchant_details_with_status( user_roles .into_iter() .map(|user_role| { + let Some(merchant_id) = &user_role.merchant_id else { + return Err(report!(UserErrors::InternalServerError)) + .attach_printable("merchant_id not found for user_role"); + }; + let Some(org_id) = &user_role.org_id else { + return Err(report!(UserErrors::InternalServerError) + .attach_printable("org_id not found in user_role")); + }; let merchant_account = merchant_account_map - .get(&user_role.merchant_id) + .get(merchant_id) .ok_or(UserErrors::InternalServerError) .attach_printable("Merchant account for user role doesn't exist")?; @@ -174,12 +195,12 @@ pub fn get_multiple_merchant_details_with_status( .attach_printable("Role info for user role doesn't exist")?; Ok(user_api::UserMerchantAccount { - merchant_id: user_role.merchant_id, + merchant_id: merchant_id.to_owned(), merchant_name: merchant_account.merchant_name.clone(), is_active: user_role.status == UserStatus::Active, role_id: user_role.role_id, role_name: role_info.get_role_name().to_string(), - org_id: user_role.org_id, + org_id: org_id.to_owned(), }) }) .collect() diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 99c020e0ee1..4fcc03b1904 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -106,11 +106,18 @@ pub async fn set_role_permissions_in_cache_by_user_role( state: &SessionState, user_role: &UserRole, ) -> bool { + let Some(ref merchant_id) = user_role.merchant_id else { + return false; + }; + + let Some(ref org_id) = user_role.org_id else { + return false; + }; set_role_permissions_in_cache_if_required( state, user_role.role_id.as_str(), - &user_role.merchant_id, - &user_role.org_id, + merchant_id, + org_id, ) .await .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) @@ -149,15 +156,18 @@ pub async fn get_multiple_role_info_for_user_roles( user_roles: &[UserRole], ) -> UserResult<Vec<roles::RoleInfo>> { futures::future::try_join_all(user_roles.iter().map(|user_role| async { - let role = roles::RoleInfo::from_role_id( - state, - &user_role.role_id, - &user_role.merchant_id, - &user_role.org_id, - ) - .await - .to_not_found_response(UserErrors::InternalServerError) - .attach_printable("Role for user role doesn't exist")?; + let Some(merchant_id) = &user_role.merchant_id else { + return Err(report!(UserErrors::InternalServerError)) + .attach_printable("merchant_id not found for user_role"); + }; + let Some(org_id) = &user_role.org_id else { + return Err(report!(UserErrors::InternalServerError) + .attach_printable("org_id not found in user_role")); + }; + let role = roles::RoleInfo::from_role_id(state, &user_role.role_id, merchant_id, org_id) + .await + .to_not_found_response(UserErrors::InternalServerError) + .attach_printable("Role for user role doesn't exist")?; Ok::<_, error_stack::Report<UserErrors>>(role) })) .await diff --git a/migrations/2024-07-23-100214_make_org_and_merchant_id_nullable_user_roles/down.sql b/migrations/2024-07-23-100214_make_org_and_merchant_id_nullable_user_roles/down.sql new file mode 100644 index 00000000000..29d51b1eb42 --- /dev/null +++ b/migrations/2024-07-23-100214_make_org_and_merchant_id_nullable_user_roles/down.sql @@ -0,0 +1,13 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE user_roles DROP CONSTRAINT user_roles_pkey; +ALTER TABLE user_roles ADD PRIMARY KEY (user_id, merchant_id); + +ALTER TABLE user_roles ALTER COLUMN org_id SET NOT NULL; +ALTER TABLE user_roles ALTER COLUMN merchant_id SET NOT NULL; + +ALTER TABLE user_roles DROP COLUMN profile_id; +ALTER TABLE user_roles DROP COLUMN entity_id; +ALTER TABLE user_roles DROP COLUMN entity_type; + +ALTER TABLE user_roles DROP COLUMN version; +DROP TYPE IF EXISTS "UserRoleVersion"; diff --git a/migrations/2024-07-23-100214_make_org_and_merchant_id_nullable_user_roles/up.sql b/migrations/2024-07-23-100214_make_org_and_merchant_id_nullable_user_roles/up.sql new file mode 100644 index 00000000000..a281c172ca0 --- /dev/null +++ b/migrations/2024-07-23-100214_make_org_and_merchant_id_nullable_user_roles/up.sql @@ -0,0 +1,20 @@ +-- Your SQL goes here +-- The below query will lock the user_roles table +-- Running this query is not necessary on higher environments +-- as the application will work fine without these queries being run +-- This query should be run after the new version of application is deployed +ALTER TABLE user_roles DROP CONSTRAINT user_roles_pkey; +-- Use the `id` column as primary key +-- This is serial and a not null column +-- So this query should not fail for not null or duplicate value reasons +ALTER TABLE user_roles ADD PRIMARY KEY (id); + +ALTER TABLE user_roles ALTER COLUMN org_id DROP NOT NULL; +ALTER TABLE user_roles ALTER COLUMN merchant_id DROP NOT NULL; + +ALTER TABLE user_roles ADD COLUMN profile_id VARCHAR(64); +ALTER TABLE user_roles ADD COLUMN entity_id VARCHAR(64); +ALTER TABLE user_roles ADD COLUMN entity_type VARCHAR(64); + +CREATE TYPE "UserRoleVersion" AS ENUM('v1', 'v2'); +ALTER TABLE user_roles ADD COLUMN version "UserRoleVersion" DEFAULT 'v1' NOT NULL;
2024-07-17T14:02:50Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description ### DB changes in user_roles - New Columns - `version` - `entity_id` - `entity_type` - `profile_id` - Changes - `merchant_id` is now nullable - `org_id` is now nullable ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#5352](https://github.com/juspay/hyperswitch/issues/5352) ## How did you test it? All these APIs should work without giving 500. - User - Signup w/ merchant id - User - Signin - User - Signin Token Only - User - Connect Account - User - Reset Password - User - Invite Multiple - User - Resend Invite - User - Accept Invite from Mail - User - Accept Invite from Mail Token only - User - Switch Merchant - User - Switch List - User - Merchants List - User - Merchants Select List - User - List - User - Verify Email - User - Verify Email Token only - User - Update User details - User Role - Update - User Role - Transfer Ownership - User Role - Accept Invite - POST - User Role - Accept Invite - PUT - User Role - Delete ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0f89a0acbfc2d55f415e0daeb27e8d9022e6a862
juspay/hyperswitch
juspay__hyperswitch-5332
Bug: set `requires_cvv` to false when either `connector_mandate_details` or `network_transaction_id` is present during MITs `requires_cvv` should be false the `recurring_enabled` should be true in the list customer payment method if the `is_connector_agnostic_mit_enabled` is enabled and `network_transaction_id` is present for that payment method.
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index db95b5c838c..24cc9583d90 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3744,6 +3744,11 @@ pub async fn list_customer_payment_method( ) .await?; + let is_connector_agnostic_mit_enabled = business_profile + .as_ref() + .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled) + .unwrap_or(false); + for pm in resp.into_iter() { let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); @@ -3861,9 +3866,20 @@ pub async fn list_customer_payment_method( state, &key_store, &merchant_account.merchant_id, + is_connector_agnostic_mit_enabled, connector_mandate_details, + pm.network_transaction_id.as_ref(), ) .await?; + + let requires_cvv = if is_connector_agnostic_mit_enabled { + requires_cvv + && !(off_session_payment_flag + && (pm.connector_mandate_details.is_some() + || pm.network_transaction_id.is_some())) + } else { + requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some()) + }; // Need validation for enabled payment method ,querying MCA let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), @@ -3883,8 +3899,7 @@ pub async fn list_customer_payment_method( bank_transfer: payment_method_retrieval_context.bank_transfer_details, bank: bank_details, surcharge_details: None, - requires_cvv: requires_cvv - && !(off_session_payment_flag && pm.connector_mandate_details.is_some()), + requires_cvv, last_used_at: Some(pm.last_used_at), default_payment_method_set: customer.default_payment_method_id.is_some() && customer.default_payment_method_id == Some(pm.payment_method_id), @@ -3982,8 +3997,13 @@ pub async fn get_mca_status( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, merchant_id: &str, + is_connector_agnostic_mit_enabled: bool, connector_mandate_details: Option<storage::PaymentsMandateReference>, + network_transaction_id: Option<&String>, ) -> errors::RouterResult<bool> { + if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() { + return Ok(true); + } if let Some(connector_mandate_details) = connector_mandate_details { let mcas = state .store diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ccca6eaed60..acfebf93046 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3503,7 +3503,8 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone let merchant_connector_id = connector_data .merchant_connector_id .as_ref() - .ok_or(errors::ApiErrorResponse::InternalServerError)?; + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to find the merchant connector id")?; if is_network_transaction_id_flow( state,
2024-07-16T06:07:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> `requires_cvv` should be false the `recurring_enabled` should be true in the list customer payment method if the `is_connector_agnostic_mit_enabled` is enabled and `network_transaction_id` is present for that payment method. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant connector account for cybersource -> Create a payment with `setup_future_usage: "off_session"` ``` { "amount": 100, "payment_type": "setup_mandate", "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_{{$timestamp}}", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "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": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "name name", "card_cvc": "737" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "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": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` ![image](https://github.com/user-attachments/assets/74c0dab4-afaf-4cd6-9b80-ae50cc5782c3) ![image](https://github.com/user-attachments/assets/ef84475f-5089-4a58-8634-18b8c6580925) -> List payment methods for the customer ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_YpbM0gAEHbx1Uv958uygtKRken4LZJL9bMFOZlgv7Obp7D4902gbF5eA5LdtGcLc' \ --header 'Content-Type: application/json' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "setup_future_usage": "off_session", "customer_id": "cu_1721110963" }' ``` ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_dubtnVf7IHNAA3NWLZsV_secret_GfGNmNO6SeHAu1h9TqxQ' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_d982e9105d8f415b99f0b30654afac74' ``` ![image](https://github.com/user-attachments/assets/68459f44-135e-42b6-b359-6ff74ac51467) -> Migrate a customer using the below endpoint ``` curl --location 'http://localhost:8080/payment_methods/migrate' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "payment_method": "card", "merchant_id": "merchant_1721063272", "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "27", "nick_name": "Joh" }, "customer_id": "cu_1721111588", "network_transaction_id": "016153570198200" } ' ``` ![image](https://github.com/user-attachments/assets/980404a8-d6c9-4126-ae3c-beea8b28b9af) ![image](https://github.com/user-attachments/assets/1944c172-fa99-4891-bd08-a9bb9e05671b) -> List payment method for the above customer ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_YpbM0gAEHbx1Uv958uygtKRken4LZJL9bMFOZlgv7Obp7D4902gbF5eA5LdtGcLc' \ --header 'Content-Type: application/json' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "setup_future_usage": "off_session", "customer_id": "cu_1721111588" }' ``` ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_EqZ9ohNIlrvelLKSA34d_secret_5kqWdqrNqexFGP8NYO2c' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_d982e9105d8f415b99f0b30654afac74' ``` ![image](https://github.com/user-attachments/assets/7ac7f46c-72e0-4d0d-b4c6-e0b7153e0705) -> Payment method entry where the connector_mandate_details is null and network transaction is present <img width="1199" alt="image" src="https://github.com/user-attachments/assets/1330d33d-3f74-485c-a366-af4d968778c5"> ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_YpbM0gAEHbx1Uv958uygtKRken4LZJL9bMFOZlgv7Obp7D4902gbF5eA5LdtGcLc' \ --header 'Content-Type: application/json' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "setup_future_usage": "off_session", "customer_id": "cu_1721111588" }' ``` <img width="964" alt="image" src="https://github.com/user-attachments/assets/6a35ac45-e8f8-4e92-a645-02a2096eaee2"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
23bfceb6c8d3bc62d1e97f1b5feaba2dbbf9bcde
juspay/hyperswitch
juspay__hyperswitch-5317
Bug: make the `original_authorized_amount` optional for MITs with `connector_mandate_details` During the MITs with the `connector_mandate_details` the `original_authorized_amount` is made optional.
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 83882b161d2..df890b53056 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -588,12 +588,30 @@ impl Some(payments::MandateReferenceId::ConnectorMandateId(_)) => { let original_amount = item .router_data - .get_recurring_mandate_payment_data()? - .get_original_payment_amount()?; + .recurring_mandate_payment_data + .as_ref() + .and_then(|recurring_mandate_payment_data| { + recurring_mandate_payment_data.original_payment_authorized_amount + }); + let original_currency = item .router_data - .get_recurring_mandate_payment_data()? - .get_original_payment_currency()?; + .recurring_mandate_payment_data + .as_ref() + .and_then(|recurring_mandate_payment_data| { + recurring_mandate_payment_data.original_payment_authorized_currency + }); + + let original_authorized_amount = match original_amount.zip(original_currency) { + Some((original_amount, original_currency)) => { + Some(utils::get_amount_as_string( + &api::CurrencyUnit::Base, + original_amount, + original_currency, + )?) + } + None => None, + }; ( None, None, @@ -601,11 +619,7 @@ impl initiator: None, merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: None, - original_authorized_amount: Some(utils::get_amount_as_string( - &api::CurrencyUnit::Base, - original_amount, - original_currency, - )?), + original_authorized_amount, previous_transaction_id: None, }), }), @@ -617,7 +631,8 @@ impl .map(|network| network.to_lowercase()) .as_deref() { - Some("discover") => { + //This is to make original_authorized_amount mandatory for discover card networks in NetworkMandateId flow + Some("004") => { let original_amount = Some( item.router_data .get_recurring_mandate_payment_data()? @@ -652,12 +667,11 @@ impl (original_amount, original_currency) } }; - - let original_authorized_amount = match (original_amount, original_currency) { - (Some(original_amount), Some(original_currency)) => Some( + let original_authorized_amount = match original_amount.zip(original_currency) { + Some((original_amount, original_currency)) => Some( utils::to_currency_base_unit(original_amount, original_currency)?, ), - _ => None, + None => None, }; commerce_indicator = "recurring".to_string(); (
2024-07-12T12:12:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> During the MITs with the `connector_mandate_details` the `original_authorized_amount` is made optional. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create cybersource merchant connector account -> Create mandate ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_FZ5RdQNZ944E16z8uT6DrqlkCa2TsEnGBFxdFu6uuNgbwi68PJlvfpYGXmqLFlJa' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_1720965634", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "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": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "name name", "card_cvc": "737" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "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": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] }' ``` <img width="888" alt="image" src="https://github.com/user-attachments/assets/389fcc01-0039-44c7-91c9-b86ee56c881c"> <img width="1451" alt="image" src="https://github.com/user-attachments/assets/5c2fdd4b-8996-49f2-903e-234540d4f1c1"> -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_FZ5RdQNZ944E16z8uT6DrqlkCa2TsEnGBFxdFu6uuNgbwi68PJlvfpYGXmqLFlJa' \ --header 'Content-Type: application/json' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "off_session": true, "customer_id": "cu_1720964758" }' ``` <img width="860" alt="image" src="https://github.com/user-attachments/assets/de232b18-1d27-4932-9b6e-ca71af7fb407"> -> List payment methods with client_secret ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_bkfuNbw8xifVm7NLOOyt_secret_xZOreIvw2iJPM39q7u6d' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_a4f83cc1e4d345ae8fc5ccf9db82cc2b' ``` <img width="931" alt="image" src="https://github.com/user-attachments/assets/e4d3d692-9f9c-4859-a66e-6044427f62de"> -> Confirm the payment with the above listed token ``` curl --location 'http://localhost:8080/payments/pay_bkfuNbw8xifVm7NLOOyt/confirm' \ --header 'api-key: pk_dev_a4f83cc1e4d345ae8fc5ccf9db82cc2b' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_s5u8wLyMPGvKIRmV6EfU", "client_secret": "pay_bkfuNbw8xifVm7NLOOyt_secret_xZOreIvw2iJPM39q7u6d", "payment_method": "card", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } } }' ``` <img width="886" alt="image" src="https://github.com/user-attachments/assets/f82652d9-41dc-47a7-b850-74ebd6738f98"> -> Make the `"original_payment_authorized_currency": "USD"` and `"original_payment_authorized_amount": 1000,` null for testing <img width="1317" alt="image" src="https://github.com/user-attachments/assets/6a9e4ad3-912c-4a2a-8478-a8093c2e2567"> -> List payment methods for customer and make a payment, verified original_authorized_amount being sent as null form logs <img width="968" alt="image" src="https://github.com/user-attachments/assets/55fcb911-31a6-42e8-b6b2-480e4e4a676f">| <img width="926" alt="image" src="https://github.com/user-attachments/assets/e049f880-5e6f-4dbd-a3dd-c642b123805b"> <img width="1274" alt="image" src="https://github.com/user-attachments/assets/c746bd9c-d4c8-4337-8b58-a1781bbd23f0"> <img width="1263" alt="image" src="https://github.com/user-attachments/assets/f5af7f82-5ebd-4d85-a9c2-ff0c80a558cb"> -> Perform the same steps with `Discover` card <img width="1119" alt="image" src="https://github.com/user-attachments/assets/ee588fbb-02b9-4b60-b60b-46e0a5a42b66"> <img width="1047" alt="image" src="https://github.com/user-attachments/assets/0ec70da9-db9f-4d58-888e-75c9daabc1f5"> <img width="957" alt="image" src="https://github.com/user-attachments/assets/047060ec-75dc-4651-8631-f19bf5ff3eef"> <img width="1263" alt="image" src="https://github.com/user-attachments/assets/630f2e1e-485e-4da7-93f8-ad813a529436"> <img width="1268" alt="image" src="https://github.com/user-attachments/assets/3e8e0b68-2db7-4aac-9895-fe75f265cfa7"> <img width="861" alt="image" src="https://github.com/user-attachments/assets/bdc71789-45bb-41af-9732-1f669b53a31e"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
21499947ad229580dd37cbbb22c31c48270bdb29
juspay/hyperswitch
juspay__hyperswitch-5300
Bug: [REFACTOR]: Correct cypress tests env variables for Payment method list testing ### Feature Description Setting Stripe as Default Pass-by for configs of response in our PaymentMethodList test scenarios. ### Possible Implementation Refactors in Cypress. ### 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!
2024-07-11T13:26:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Setting Stripe as Default Pass-by for configs of response in our PaymentMethodList test scenarios. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Ran Cypress tests on Local: <img width="423" alt="Screenshot 2024-07-11 at 6 55 48 PM" src="https://github.com/juspay/hyperswitch/assets/61520228/6a8ae2ad-363c-4983-8736-c295010fe500"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
43741df4a76a66faa472dacd66b396232a2fbdbf
juspay/hyperswitch
juspay__hyperswitch-5307
Bug: fix(bug): remove extra underscrore character in between email footer icons remove extra underscrore character in between email footer icons
diff --git a/crates/router/src/services/email/assets/api_key_expiry_reminder.html b/crates/router/src/services/email/assets/api_key_expiry_reminder.html index 6ebb099ed74..9d97d153eb6 100644 --- a/crates/router/src/services/email/assets/api_key_expiry_reminder.html +++ b/crates/router/src/services/email/assets/api_key_expiry_reminder.html @@ -125,7 +125,7 @@ </td> </tr> <tr> - <td> + <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html index 02f646c010d..8035728d4c7 100644 --- a/crates/router/src/services/email/assets/bizemailprod.html +++ b/crates/router/src/services/email/assets/bizemailprod.html @@ -135,7 +135,7 @@ </td> </tr> <tr> - <td> + <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" diff --git a/crates/router/src/services/email/assets/invite.html b/crates/router/src/services/email/assets/invite.html index 7c7beb317fb..4a2a6835e80 100644 --- a/crates/router/src/services/email/assets/invite.html +++ b/crates/router/src/services/email/assets/invite.html @@ -180,7 +180,7 @@ </td> </tr> <tr> - <td> + <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" diff --git a/crates/router/src/services/email/assets/magic_link.html b/crates/router/src/services/email/assets/magic_link.html index 27f0b9816ef..b7516e8ae09 100644 --- a/crates/router/src/services/email/assets/magic_link.html +++ b/crates/router/src/services/email/assets/magic_link.html @@ -179,7 +179,7 @@ </td> </tr> <tr> - <td> + <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" diff --git a/crates/router/src/services/email/assets/recon_activation.html b/crates/router/src/services/email/assets/recon_activation.html index 53ee8386380..512bda73227 100644 --- a/crates/router/src/services/email/assets/recon_activation.html +++ b/crates/router/src/services/email/assets/recon_activation.html @@ -152,7 +152,7 @@ </td> </tr> <tr> - <td> + <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" diff --git a/crates/router/src/services/email/assets/reset.html b/crates/router/src/services/email/assets/reset.html index 1aa6b1b50e9..e50ea598976 100644 --- a/crates/router/src/services/email/assets/reset.html +++ b/crates/router/src/services/email/assets/reset.html @@ -177,7 +177,7 @@ </td> </tr> <tr> - <td> + <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" diff --git a/crates/router/src/services/email/assets/verify.html b/crates/router/src/services/email/assets/verify.html index 7b56b79abdf..d67d130a75f 100644 --- a/crates/router/src/services/email/assets/verify.html +++ b/crates/router/src/services/email/assets/verify.html @@ -145,7 +145,7 @@ </td> </tr> <tr> - <td> + <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank"
2024-07-11T09:26:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Minor bugfix in Email templates footer icon, an extra character. was appearing that is now removed Current ![image](https://github.com/juspay/hyperswitch/assets/96485413/a49d43d1-2df2-498a-acc7-894b5bfe6853) New ![image](https://github.com/juspay/hyperswitch/assets/96485413/d43e0947-8455-4a87-96c3-3351527e4b0a) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
998ce02ebc1eed10e426987d1af9c02d1f1735fe
juspay/hyperswitch
juspay__hyperswitch-5298
Bug: [BUG] : [razorpay] wrong refund webhook reference id ### Bug Description Because of wrong refund webhook reference id, refund webhooks are failing while received by hyperswitch ### Expected Behavior Hyperswitch should identify the refund and trigger a Rsync to update the status. ### Actual Behavior Hyperswitch does not identify the refund and refund remain in pending status ### 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/razorpay.rs b/crates/router/src/connector/razorpay.rs index 15fac492120..737ead477c3 100644 --- a/crates/router/src/connector/razorpay.rs +++ b/crates/router/src/connector/razorpay.rs @@ -630,7 +630,7 @@ impl api::IncomingWebhook for Razorpay { let webhook_resource_object = get_webhook_object_from_body(request.body)?; match webhook_resource_object.refund { Some(refund_data) => Ok(api_models::webhooks::ObjectReferenceId::RefundId( - api_models::webhooks::RefundIdType::RefundId(refund_data.entity.id), + api_models::webhooks::RefundIdType::ConnectorRefundId(refund_data.entity.id), )), None => Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId(
2024-07-11T12:39:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently we are passing a wrong refund webhook reference id, hence refund webhooks are failing while received by hyperswitch. After this PR Hyperswitch should identify refund webhook and trigger a Rsync to update the status ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a payment with Razorpay UPI Collect ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UlJFXb4LACytmSXSI3i9J9N6aFzJELAUCypIwcylOhr5nhhGr6wOioIxQ52KGuDb' \ --data-raw '{ "amount": 5000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "IatapayCustomer", "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": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "9490419802@ybl" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "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" } }' ``` Response ``` { "payment_id": "pay_3mp411CRviQIHXlLmjJY", "merchant_id": "merchant_1720626789", "status": "processing", "amount": 5000, "net_amount": 5000, "amount_capturable": 0, "amount_received": null, "connector": "razorpay", "client_secret": "pay_3mp411CRviQIHXlLmjJY_secret_cjQr2JxXyhYbKgOHZouw", "created": "2024-07-11T12:16:11.242Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "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": "upi", "payment_method_data": { "upi": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "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": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_collect", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "IatapayCustomer", "created_at": 1720700171, "expires": 1720703771, "secret": "epk_163c8836572b47cba27465fe8b7a622e" }, "manual_retry_allowed": false, "connector_transaction_id": "pay_OXK0gn9yX2qv0N", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_3mp411CRviQIHXlLmjJY_1", "payment_link": null, "profile_id": "pro_onmiv6JSZNIGR84hhQ05", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LP7o6Xf3hAyiIpcIQA8C", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-11T12:31:11.242Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-11T12:16:13.722Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` 2. Do a force Psync ``` curl --location 'localhost:8080/payments/pay_3mp411CRviQIHXlLmjJY?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key:' ``` Response ``` { "payment_id": "pay_3mp411CRviQIHXlLmjJY", "merchant_id": "merchant_1720626789", "status": "succeeded", "amount": 5000, "net_amount": 5000, "amount_capturable": 0, "amount_received": 5000, "connector": "razorpay", "client_secret": "pay_3mp411CRviQIHXlLmjJY_secret_cjQr2JxXyhYbKgOHZouw", "created": "2024-07-11T12:16:11.242Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "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": "upi", "payment_method_data": { "upi": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "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": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_collect", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pay_OXK0gn9yX2qv0N", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_3mp411CRviQIHXlLmjJY_1", "payment_link": null, "profile_id": "pro_onmiv6JSZNIGR84hhQ05", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LP7o6Xf3hAyiIpcIQA8C", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-11T12:31:11.242Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-11T12:16:30.610Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` 3. Create a refund ``` curl --location 'localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_UlJFXb4LACytmSXSI3i9J9N6aFzJELAUCypIwcylOhr5nhhGr6wOioIxQ52KGuDb' \ --data '{ "payment_id": "pay_3mp411CRviQIHXlLmjJY", "amount": 5000, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` { "refund_id": "ref_tgRu9lJFmOlsx52KiWL9", "payment_id": "pay_3mp411CRviQIHXlLmjJY", "amount": 5000, "currency": "INR", "status": "pending", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "created_at": "2024-07-11T12:16:36.811Z", "updated_at": "2024-07-11T12:16:36.811Z", "connector": "razorpay", "profile_id": "pro_onmiv6JSZNIGR84hhQ05", "merchant_connector_id": "mca_LP7o6Xf3hAyiIpcIQA8C", "charges": null } ``` 4. Wait untill the refund gets succeeded at Razorpay. Before refund sync, check the refund table in the DB for refund status <img width="1642" alt="Screenshot 2024-07-11 at 5 49 02 PM" src="https://github.com/juspay/hyperswitch/assets/131388445/a91e03b3-1e2a-4bfb-828e-f2834181d3be"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
4e41827ade5a4c844cbc8822618ac2e35c6029e2
juspay/hyperswitch
juspay__hyperswitch-5313
Bug: Add batch api to migrate multiple payment methods at a time #5242 In addition to this API, when merchants have multiple payment methods to migrate we are adding support to upload them as CSV and do the migration including below 2 steps 1. Create the customer if it is not already present 2. Create the payment method and add the connector details if passed Sample payload: ``` merchant_id,merchant_connector_id,name,email,phone,phone_country_code,customer_id,subscription_id,payment_method,payment_method_type,nick_name,payment_instrument_id,card_number_masked,card_expiry_month,card_expiry_year,card_scheme,original_transaction_id,billing_address_zip,billing_address_state,billing_address_first_name,billing_address_last_name,billing_address_city,billing_address_country,billing_address_line1,billing_address_line2,raw_card_number,original_transaction_amount,original_transaction_currency merchant_1720684811,mca_qqgmyxXRtsEjRLAUHBD4,noreal name,test@gmail.com,523698741,33,958709111eda444cdfdb2e8b7a3,900036959,card,credit,,4CBB27C05DE063AF598E,433026XXXXXX4675,03,2027,1,16153570198,94043,CA,NOREAL,NAME,Mountain View,US,1295 Charleston Rd,,,1000,USD merchant_1720684811,mca_qqgmyxXRtsEjRLAUHBD4,john doe,test1@gmail.com,9159999999,1,dbc00f611eea04f024251790ff4,9000369592,card,credit,,F7A6049ADFE063AF598,378282XXXXX0005,03,2024,3,52127621321,700000,AK,NOREAL,NAME,hcm,US,hcm,,,, ```
diff --git a/Cargo.lock b/Cargo.lock index 68792185b1b..c0e6b05c845 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2397,6 +2397,27 @@ dependencies = [ "typenum", ] +[[package]] +name = "csv" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac574ff4d437a7b5ad237ef331c17ccca63c46479e5b5453eb8e10bb99a759fe" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "csv-core" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efa2b3d7902f4b634a20cae3c9c4e6209dc4779feb6863329607560143efa70" +dependencies = [ + "memchr", +] + [[package]] name = "currency_conversion" version = "0.1.0" @@ -6093,6 +6114,7 @@ dependencies = [ "common_utils", "config", "cookie 0.18.1", + "csv", "currency_conversion", "derive_deref", "diesel", diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 7b33e3dfeab..7799cc24df2 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -7,13 +7,14 @@ use common_utils::{ id_type, link_utils, pii, types::{MinorUnit, Percentage, Surcharge}, }; +use masking::PeekInterface; use serde::de; use utoipa::{schema, ToSchema}; #[cfg(feature = "payouts")] use crate::payouts; use crate::{ - admin, enums as api_enums, + admin, customers, enums as api_enums, payments::{self, BankCodeResponse}, }; @@ -1335,3 +1336,177 @@ pub struct TokenizedBankRedirectValue1 { pub struct TokenizedBankRedirectValue2 { pub customer_id: Option<id_type::CustomerId>, } + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct PaymentMethodRecord { + pub customer_id: id_type::CustomerId, + pub name: Option<masking::Secret<String>>, + pub email: Option<pii::Email>, + pub phone: Option<masking::Secret<String>>, + pub phone_country_code: Option<String>, + pub merchant_id: String, + pub payment_method: Option<api_enums::PaymentMethod>, + pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub nick_name: masking::Secret<String>, + pub payment_instrument_id: masking::Secret<String>, + pub card_number_masked: masking::Secret<String>, + pub card_expiry_month: masking::Secret<String>, + pub card_expiry_year: masking::Secret<String>, + pub card_scheme: Option<String>, + pub original_transaction_id: String, + pub billing_address_zip: masking::Secret<String>, + pub billing_address_state: masking::Secret<String>, + pub billing_address_first_name: masking::Secret<String>, + pub billing_address_last_name: masking::Secret<String>, + pub billing_address_city: String, + pub billing_address_country: Option<api_enums::CountryAlpha2>, + pub billing_address_line1: masking::Secret<String>, + pub billing_address_line2: Option<masking::Secret<String>>, + pub billing_address_line3: Option<masking::Secret<String>>, + pub raw_card_number: Option<masking::Secret<String>>, + pub merchant_connector_id: String, + pub original_transaction_amount: Option<i64>, + pub original_transaction_currency: Option<common_enums::Currency>, + pub line_number: Option<i64>, +} + +#[derive(Debug, Default, serde::Serialize)] +pub struct PaymentMethodMigrationResponse { + pub line_number: Option<i64>, + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_id: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option<api_enums::PaymentMethod>, + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub customer_id: Option<id_type::CustomerId>, + pub migration_status: MigrationStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub migration_error: Option<String>, + pub card_number_masked: Option<masking::Secret<String>>, +} + +#[derive(Debug, Default, serde::Serialize)] +pub enum MigrationStatus { + Success, + #[default] + Failed, +} + +type PaymentMethodMigrationResponseType = + (Result<PaymentMethodResponse, String>, PaymentMethodRecord); +impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse { + fn from((response, record): PaymentMethodMigrationResponseType) -> Self { + match response { + Ok(res) => Self { + payment_method_id: Some(res.payment_method_id), + payment_method: res.payment_method, + payment_method_type: res.payment_method_type, + customer_id: res.customer_id, + migration_status: MigrationStatus::Success, + migration_error: None, + card_number_masked: Some(record.card_number_masked), + line_number: record.line_number, + }, + Err(e) => Self { + customer_id: Some(record.customer_id), + migration_status: MigrationStatus::Failed, + migration_error: Some(e), + card_number_masked: Some(record.card_number_masked), + line_number: record.line_number, + ..Self::default() + }, + } + } +} + +impl From<PaymentMethodRecord> for PaymentMethodMigrate { + fn from(record: PaymentMethodRecord) -> Self { + let mut mandate_reference = HashMap::new(); + mandate_reference.insert( + record.merchant_connector_id, + PaymentsMandateReferenceRecord { + connector_mandate_id: record.payment_instrument_id.peek().to_string(), + payment_method_type: record.payment_method_type, + original_payment_authorized_amount: record + .original_transaction_amount + .or(Some(1000)), + original_payment_authorized_currency: record + .original_transaction_currency + .or(Some(common_enums::Currency::USD)), + }, + ); + Self { + merchant_id: record.merchant_id, + customer_id: Some(record.customer_id), + card: Some(MigrateCardDetail { + card_number: record.raw_card_number.unwrap_or(record.card_number_masked), + card_exp_month: record.card_expiry_month, + card_exp_year: record.card_expiry_year, + card_holder_name: record.name, + card_network: None, + card_type: None, + card_issuer: None, + card_issuing_country: None, + nick_name: Some(record.nick_name), + }), + payment_method: record.payment_method, + payment_method_type: record.payment_method_type, + payment_method_issuer: None, + billing: Some(payments::Address { + address: Some(payments::AddressDetails { + city: Some(record.billing_address_city), + country: record.billing_address_country, + line1: Some(record.billing_address_line1), + line2: record.billing_address_line2, + state: Some(record.billing_address_state), + line3: record.billing_address_line3, + zip: Some(record.billing_address_zip), + first_name: Some(record.billing_address_first_name), + last_name: Some(record.billing_address_last_name), + }), + phone: Some(payments::PhoneDetails { + number: record.phone, + country_code: record.phone_country_code, + }), + email: record.email, + }), + connector_mandate_details: Some(PaymentsMandateReference(mandate_reference)), + metadata: None, + payment_method_issuer_code: None, + card_network: None, + #[cfg(feature = "payouts")] + bank_transfer: None, + #[cfg(feature = "payouts")] + wallet: None, + payment_method_data: None, + network_transaction_id: record.original_transaction_id.into(), + } + } +} + +impl From<PaymentMethodRecord> for customers::CustomerRequest { + fn from(record: PaymentMethodRecord) -> Self { + Self { + customer_id: Some(record.customer_id), + merchant_id: record.merchant_id, + name: record.name, + email: record.email, + phone: record.phone, + description: None, + phone_country_code: record.phone_country_code, + address: Some(payments::AddressDetails { + city: Some(record.billing_address_city), + country: record.billing_address_country, + line1: Some(record.billing_address_line1), + line2: record.billing_address_line2, + state: Some(record.billing_address_state), + line3: record.billing_address_line3, + zip: Some(record.billing_address_zip), + first_name: Some(record.billing_address_first_name), + last_name: Some(record.billing_address_last_name), + }), + metadata: None, + } + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 4373c7fb169..108b035ec0f 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -51,6 +51,7 @@ bytes = "1.6.0" clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.14.0", features = ["toml"] } cookie = "0.18.1" +csv = "1.3.0" diesel = { version = "2.1.5", features = ["postgres"] } digest = "0.10.7" dyn-clone = "1.0.17" diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index ad1a292df09..c0e0291b8c4 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -470,3 +470,28 @@ pub async fn update_customer( customers::CustomerResponse::from((response, update_customer.address)), )) } + +pub async fn migrate_customers( + state: SessionState, + customers: Vec<customers::CustomerRequest>, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, +) -> errors::CustomerResponse<()> { + for customer in customers { + match create_customer( + state.clone(), + merchant_account.clone(), + key_store.clone(), + customer, + ) + .await + { + Ok(_) => (), + Err(e) => match e.current_context() { + errors::CustomersErrorResponse::CustomerAlreadyExists => (), + _ => return Err(e), + }, + } + } + Ok(services::ApplicationResponse::Json(())) +} diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 6fcd27fefd0..a7a87b6d96e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1,4 +1,5 @@ pub mod cards; +pub mod migration; pub mod surcharge_decision_configs; pub mod transformers; pub mod utils; diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 33e188b8ca0..db95b5c838c 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -269,23 +269,10 @@ pub async fn get_or_insert_payment_method( pub async fn migrate_payment_method( state: routes::SessionState, req: api::PaymentMethodMigrate, + merchant_id: &str, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { - let merchant_id = &req.merchant_id; - 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(errors::ApiErrorResponse::MerchantAccountNotFound)?; - - let merchant_account = state - .store - .find_merchant_account_by_merchant_id(merchant_id, &key_store) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let card_details = req.card.as_ref().get_required_value("card")?; let card_number_validation_result = @@ -294,7 +281,7 @@ pub async fn migrate_payment_method( if let Some(connector_mandate_details) = &req.connector_mandate_details { helpers::validate_merchant_connector_ids_in_connector_mandate_details( &*state.store, - &key_store, + key_store, connector_mandate_details, merchant_id, ) @@ -311,8 +298,8 @@ pub async fn migrate_payment_method( get_client_secret_or_add_payment_method( state, payment_method_create_request, - &merchant_account, - &key_store, + merchant_account, + key_store, ) .await } @@ -322,8 +309,8 @@ pub async fn migrate_payment_method( state, &req, merchant_id.into(), - &key_store, - &merchant_account, + key_store, + merchant_account, ) .await } @@ -513,7 +500,10 @@ pub async fn skip_locker_call_and_migrate_payment_method( payment_method: req.payment_method, payment_method_type: req.payment_method_type, payment_method_issuer: req.payment_method_issuer.clone(), - scheme: req.card_network.clone(), + scheme: req + .card_network + .clone() + .or(card.clone().and_then(|card| card.scheme.clone())), metadata: payment_method_metadata.map(Secret::new), payment_method_data: payment_method_data_encrypted.map(Into::into), connector_mandate_details: Some(connector_mandate_details), diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/router/src/core/payment_methods/migration.rs new file mode 100644 index 00000000000..83e9993478b --- /dev/null +++ b/crates/router/src/core/payment_methods/migration.rs @@ -0,0 +1,85 @@ +use actix_multipart::form::{bytes::Bytes, MultipartForm}; +use api_models::payment_methods::{PaymentMethodMigrationResponse, PaymentMethodRecord}; +use csv::Reader; +use rdkafka::message::ToBytes; + +use crate::{ + core::{errors, payment_methods::cards::migrate_payment_method}, + routes, services, + types::{api, domain}, +}; + +pub async fn migrate_payment_methods( + state: routes::SessionState, + payment_methods: Vec<PaymentMethodRecord>, + merchant_id: &str, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, +) -> errors::RouterResponse<Vec<PaymentMethodMigrationResponse>> { + let mut result = Vec::new(); + for record in payment_methods { + let res = migrate_payment_method( + state.clone(), + api::PaymentMethodMigrate::from(record.clone()), + merchant_id, + merchant_account, + key_store, + ) + .await; + result.push(PaymentMethodMigrationResponse::from(( + match res { + Ok(services::api::ApplicationResponse::Json(response)) => Ok(response), + Err(e) => Err(e.to_string()), + _ => Err("Failed to migrate payment method".to_string()), + }, + record, + ))); + } + Ok(services::api::ApplicationResponse::Json(result)) +} + +#[derive(Debug, MultipartForm)] +pub struct PaymentMethodsMigrateForm { + #[multipart(limit = "1MB")] + pub file: Bytes, +} + +fn parse_csv(data: &[u8]) -> csv::Result<Vec<PaymentMethodRecord>> { + let mut csv_reader = Reader::from_reader(data); + let mut records = Vec::new(); + let mut id_counter = 0; + for result in csv_reader.deserialize() { + let mut record: PaymentMethodRecord = result?; + id_counter += 1; + record.line_number = Some(id_counter); + records.push(record); + } + Ok(records) +} +pub fn get_payment_method_records( + form: PaymentMethodsMigrateForm, +) -> Result<(String, Vec<PaymentMethodRecord>), errors::ApiErrorResponse> { + match parse_csv(form.file.data.to_bytes()) { + Ok(records) => { + if let Some(first_record) = records.first() { + if records + .iter() + .all(|merchant_id| merchant_id.merchant_id == first_record.merchant_id) + { + Ok((first_record.merchant_id.clone(), records)) + } else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Only one merchant id can be updated at a time".to_string(), + }) + } + } else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "No records found".to_string(), + }) + } + } + Err(e) => Err(errors::ApiErrorResponse::PreconditionFailed { + message: e.to_string(), + }), + } +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d82f98f295d..b8b329a3acb 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -934,6 +934,9 @@ impl PaymentMethods { .service( web::resource("/migrate").route(web::post().to(migrate_payment_method_api)), ) + .service( + web::resource("/migrate-batch").route(web::post().to(migrate_payment_methods)), + ) .service( web::resource("/collect").route(web::post().to(initiate_pm_collect_link_flow)), ) diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 8ff6e48237c..003cd71c00d 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -1,18 +1,25 @@ +use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; use common_utils::{errors::CustomResult, id_type}; use diesel_models::enums::IntentStatus; use error_stack::ResultExt; +use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use router_env::{instrument, logger, tracing, Flow}; use super::app::{AppState, SessionState}; use crate::{ core::{ - api_locking, errors, - payment_methods::{self as payment_methods_routes, cards}, + api_locking, customers, errors, + errors::utils::StorageErrorExt, + payment_methods::{self as payment_methods_routes, cards, migration}, }, services::{api, authentication as auth, authorization::permissions::Permission}, types::{ - api::payment_methods::{self, PaymentMethodId}, + api::{ + customers::CustomerRequest, + payment_methods::{self, PaymentMethodId}, + }, + domain, storage::payment_method::PaymentTokenData, }, utils::Encode, @@ -59,7 +66,84 @@ pub async fn migrate_payment_method_api( state, &req, json_payload.into_inner(), - |state, _, req, _| async move { Box::pin(cards::migrate_payment_method(state, req)).await }, + |state, _, req, _| async move { + let merchant_id = req.merchant_id.clone(); + let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; + Box::pin(cards::migrate_payment_method( + state, + req, + &merchant_id, + &merchant_account, + &key_store, + )) + .await + }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +async fn get_merchant_account( + state: &SessionState, + merchant_id: &str, +) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> { + 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(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + Ok((key_store, merchant_account)) +} + +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))] +pub async fn migrate_payment_methods( + state: web::Data<AppState>, + req: HttpRequest, + MultipartForm(form): MultipartForm<migration::PaymentMethodsMigrateForm>, +) -> HttpResponse { + let flow = Flow::PaymentMethodsMigrate; + let (merchant_id, records) = match migration::get_payment_method_records(form) { + Ok((merchant_id, records)) => (merchant_id, records), + Err(e) => return api::log_and_return_error_response(e.into()), + }; + let merchant_id = merchant_id.as_str(); + Box::pin(api::server_wrap( + flow, + state, + &req, + records, + |state, _, req, _| async move { + let (key_store, merchant_account) = get_merchant_account(&state, merchant_id).await?; + // Create customers if they are not already present + customers::migrate_customers( + state.clone(), + req.iter() + .map(|e| CustomerRequest::from(e.clone())) + .collect(), + merchant_account.clone(), + key_store.clone(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + Box::pin(migration::migrate_payment_methods( + state, + req, + merchant_id, + &merchant_account, + &key_store, + )) + .await + }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 540c67c5762..1a488721905 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -740,7 +740,15 @@ pub enum AuthFlow { #[allow(clippy::too_many_arguments)] #[instrument( - skip(request, payload, state, func, api_auth, request_state), + skip( + request, + payload, + state, + func, + api_auth, + request_state, + incoming_request_header + ), fields(merchant_id) )] pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>(
2024-07-12T07:12:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Merchants who has existing customer payment methods in payment processor can upload a csv file to migrate their customers and their payment methods using this `/migrate-bulk` API ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 provide seamless experience to customers when merchant moves from payment processor to hyperswitch ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Add below records and see if the new customer and payment methods are created. try making a recurring payment with the payment method saved ``` merchant_id,merchant_connector_id,name,email,phone,phone_country_code,customer_id,subscription_id,payment_method,payment_method_type,nick_name,payment_instrument_id,card_number_masked,card_expiry_month,card_expiry_year,card_scheme,original_transaction_id,billing_address_zip,billing_address_state,billing_address_first_name,billing_address_last_name,billing_address_city,billing_address_country,billing_address_line1,billing_address_line2,raw_card_number,original_transaction_amount,original_transaction_currency merchant_1720684811,mca_qqgmyxXRtsEjRLAUHBD4,noreal name,test@gmail.com,523698741,33,958709111eda444cdfdb2e8b7a3,900036959,card,credit,,4CBB27C05DE063AF598E,433026XXXXXX4675,03,2027,1,16153570198,94043,CA,NOREAL,NAME,Mountain View,US,1295 Charleston Rd,,,1000,USD merchant_1720684811,mca_qqgmyxXRtsEjRLAUHBD4,john doe,test1@gmail.com,9159999999,1,dbc00f611eea04f024251790ff4,9000369592,card,credit,,F7A6049ADFE063AF598,378282XXXXX0005,03,2024,3,52127621321,700000,AK,NOREAL,NAME,hcm,US,hcm,,,, ``` ``` curl --location 'http://localhost:8080/payment_methods/migrate-batch' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --form 'file=@"/Users/jagan.elavarasan/Downloads/sample.csv"' ``` <img width="1000" alt="image" src="https://github.com/user-attachments/assets/ba2e3ccc-ccf8-48d9-b148-931aea4cfe3f"> ``` curl --location 'http://localhost:8080/customers/edca1edee0e411ec961c506b8dc695e7/payment_methods' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom-be' \ --header 'api-key: dev_hRgXc8VdzglIywDYBmC7MBpw7dNGIAniCGRdqrF7cDdkWLoGi2iMfEI83pVGz2zz' ``` <img width="694" alt="image" src="https://github.com/user-attachments/assets/d96af05c-1b40-4fce-831d-eb220b4cb8d0"> ``` curl --location 'http://localhost:8080/payments/pay_xAY8tQGtAijAhFX4a4pq/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_3a60113d6c90405d99a563e78961880b' \ --data '{ "payment_method": "card", "client_secret": "pay_xAY8tQGtAijAhFX4a4pq_secret_AgGaWFPSW3inNKcxkHcg", "payment_token": "token_3VdfjykAKGS1ukxixQoM" }' ``` <img width="627" alt="image" src="https://github.com/user-attachments/assets/45ad03c2-1947-491c-b841-b55bea3ad20c"> 2. Try uploading big file > 1MB, it should throw appropriate error ``` curl --location 'http://localhost:8080/payment_methods/migrate-batch' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --form 'file=@"/Users/jagan.elavarasan/Downloads/sample.csv"' ``` <img width="595" alt="image" src="https://github.com/user-attachments/assets/47adf4a9-3c28-40a8-b715-e400238bed78"> 3. Try uploading mulitple merchant at a time, it should not be allowed <img width="555" alt="image" src="https://github.com/user-attachments/assets/a1af5dcb-168f-43b1-846c-af782333bcd7"> 4. Should not allow merchant or merchant_connector_account if not created before <img width="567" alt="Screenshot 2024-07-12 at 15 06 50" src="https://github.com/user-attachments/assets/e3992488-b965-457d-810b-56c85db8dab6"> <img width="1012" alt="image" src="https://github.com/user-attachments/assets/95b8186a-06e8-4d1e-ad04-702e94703482"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f24a4070c33a435f25be9511fe1b90cf337efa52
juspay/hyperswitch
juspay__hyperswitch-5292
Bug: [REFACTOR] List the Payment Methods Based on the Connector Type ### Feature Description List the Payment Methods Based on the Connector Type being Payment Processor ### Possible Implementation List the Payment Methods Based on the Connector Type being Payment Processor ### 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!
2024-06-07T09:14:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description List the Payment Methods for Merchant , based on the connector type, to differentiate between Payments and Payouts Processors ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? - Create a MA - Create two MCA , one with the `connector_type : "payment_processor"` other with the connector type as `payout_processor` - Create a payment - Do a list of Pms for the Merchant Account, BOA would not be here as its connector_type is `payout_processor`, cause here only the PMs with `payment_processor` would get listed ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": {}, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "stripe" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "stripe" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "new_mandate", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
37e34e3bfde9281b3a69b0769c901a887dcf400f
juspay/hyperswitch
juspay__hyperswitch-5271
Bug: fix(analytics): Update frm clickhouse script for creating table https://github.com/juspay/hyperswitch/blob/main/crates/analytics/docs/clickhouse/scripts/fraud_check.sql In this sql file there is a minor bug while creating the table which needs to be fixed.
diff --git a/crates/analytics/docs/clickhouse/scripts/fraud_check.sql b/crates/analytics/docs/clickhouse/scripts/fraud_check.sql index 19e535981b6..30788a2a0f7 100644 --- a/crates/analytics/docs/clickhouse/scripts/fraud_check.sql +++ b/crates/analytics/docs/clickhouse/scripts/fraud_check.sql @@ -49,7 +49,7 @@ CREATE TABLE fraud_check ( `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), `last_step` LowCardinality(String), `payment_capture_method` LowCardinality(String), - `sign_flag` Int8 + `sign_flag` Int8, INDEX frmNameIndex frm_name TYPE bloom_filter GRANULARITY 1, INDEX frmStatusIndex frm_status TYPE bloom_filter GRANULARITY 1, INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, diff --git a/crates/analytics/docs/clickhouse/scripts/sdk_events.sql b/crates/analytics/docs/clickhouse/scripts/sdk_events.sql index 7a8bc9d9c3d..bfe6401cacc 100644 --- a/crates/analytics/docs/clickhouse/scripts/sdk_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/sdk_events.sql @@ -209,7 +209,7 @@ CREATE TABLE active_payments ( `merchant_id` String, `created_at` DateTime64, `flow_type` LowCardinality(Nullable(String)), - INDEX merchantIndex merchant_id TYPE bloom_filter GRANULARITY 1 + INDEX merchantIndex merchant_id TYPE bloom_filter GRANULARITY 1, INDEX flowTypeIndex flow_type TYPE bloom_filter GRANULARITY 1 ) ENGINE = MergeTree PARTITION BY toStartOfSecond(created_at)
2024-07-10T09:09:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Fixed the issue, a comma was missed in the syntax ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Fix the bug ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Script ran fine, and the fraud check tables were created in clickhouse ![image](https://github.com/juspay/hyperswitch/assets/89402434/8fe6e07e-8264-40ad-8079-aca5f042309c) ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
3da93f1f73680cc20313a068aacae3018b067b45
juspay/hyperswitch
juspay__hyperswitch-5269
Bug: Bug(router): [iatapay] make source verification false ### Bug Description make source verification false ### Expected Behavior make source verification false ### Actual Behavior make source verification true ### 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/razorpay.rs b/crates/router/src/connector/razorpay.rs index 836f71e3c17..195508dffa2 100644 --- a/crates/router/src/connector/razorpay.rs +++ b/crates/router/src/connector/razorpay.rs @@ -7,6 +7,7 @@ use common_utils::{ use error_stack::{Report, ResultExt}; use masking::ExposeInterface; use transformers as razorpay; +use types::domain; use super::utils::{self as connector_utils}; use crate::{ @@ -640,6 +641,16 @@ impl api::IncomingWebhook for Razorpay { } } + async fn verify_webhook_source( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + _merchant_account: &domain::MerchantAccount, + _merchant_connector_account: domain::MerchantConnectorAccount, + _connector_label: &str, + ) -> CustomResult<bool, errors::ConnectorError> { + Ok(false) + } + fn get_webhook_event_type( &self, request: &api::IncomingWebhookRequestDetails<'_>,
2024-07-10T07:41:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Make source verification false ## Test case 1.Create a payment ``` curl --location '/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_apY4Z0olECTOs9jaEXdLerWGTjFwlPexZBWUQn9t1Cd09ebyn8yGS2nT6JPFTZj8' \ --data-raw '{ "amount": 5000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "IatapayCustomer", "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": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "9490419802@ybl" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "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" } }' ``` Response ``` { "payment_id": "pay_WAAzfjsctlcdUrzH9xkE", "merchant_id": "merchant_1720594913", "status": "processing", "amount": 5000, "net_amount": 5000, "amount_capturable": 0, "amount_received": null, "connector": "razorpay", "client_secret": "pay_WAAzfjsctlcdUrzH9xkE_secret_8088buGs1u1ap6E9FjpE", "created": "2024-07-10T07:50:20.842Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "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": "upi", "payment_method_data": { "upi": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "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": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_collect", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "IatapayCustomer", "created_at": 1720597820, "expires": 1720601420, "secret": "epk_de254e2a2a33497a97ecfd9da200f600" }, "manual_retry_allowed": false, "connector_transaction_id": "pay_OWqwkXOxq3rZ3W", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_WAAzfjsctlcdUrzH9xkE_1", "payment_link": null, "profile_id": "pro_mYw8etRKZnk71NJpkTy0", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_18RYgzKYRC2gHtTEvSaP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-10T08:05:20.842Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-10T07:50:23.281Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` 2. Psync without force sync ``` curl --location '/payments/pay_csYqvibT29ZV6YqCPogo' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_apY4Z0olECTOs9jaEXdLerWGTjFwlPexZBWUQn9t1Cd09ebyn8yGS2nT6JPFTZj8' ``` Response ```{ "payment_id": "pay_elkpZLoo2uBzythuy73k", "merchant_id": "merchant_1720594913", "status": "succeeded", "amount": 5000, "net_amount": 5000, "amount_capturable": 0, "amount_received": null, "connector": "razorpay", "client_secret": "pay_elkpZLoo2uBzythuy73k_secret_j3zBwbCJn2TCpUc6srvm", "created": "2024-07-10T07:46:02.270Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "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": "upi", "payment_method_data": { "upi": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "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": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_collect", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pay_OWqsD5F3qaxHJl", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_elkpZLoo2uBzythuy73k_1", "payment_link": null, "profile_id": "pro_mYw8etRKZnk71NJpkTy0", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_18RYgzKYRC2gHtTEvSaP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-10T08:01:02.270Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-10T07:46:05.359Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
fa7add19eeb09f8ab12970fa8ed66270f45883c3
juspay/hyperswitch
juspay__hyperswitch-5261
Bug: [REFACTOR]: Removal of create_encrypted_data_optional function ### Feature Description `create_encrypted_data_optional` is a copy of `create_encrypted_data` the only difference being in the params the former takes Option<T> and the latter takes T. ### Possible Implementation Refactoring the function and places where all it is used. ### 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 ee6ac7731c2..33e188b8ca0 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -46,6 +46,8 @@ use super::surcharge_decision_configs::{ }; #[cfg(not(feature = "connector_choice_mca_id"))] use crate::core::utils::get_connector_label; +#[cfg(feature = "payouts")] +use crate::types::domain::types::AsyncLift; use crate::{ configs::settings, core::{ @@ -67,10 +69,7 @@ use crate::{ services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, - domain::{ - self, - types::{decrypt, encrypt_optional, AsyncLift}, - }, + domain::{self, types::decrypt}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, @@ -351,9 +350,14 @@ pub async fn skip_locker_call_and_migrate_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse connector mandate details")?; - let payment_method_billing_address = create_encrypted_data(key_store, req.billing.clone()) + let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req + .billing + .clone() + .async_map(|billing| create_encrypted_data(key_store, billing)) .await - .map(|details| details.into()); + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt Payment method billing address")?; let customer = db .find_customer_by_customer_id_merchant_id( @@ -484,10 +488,13 @@ pub async fn skip_locker_call_and_migrate_payment_method( .as_ref() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); - let payment_method_data_encrypted = - create_encrypted_data(key_store, payment_method_card_details) + let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = + payment_method_card_details + .async_map(|card_details| create_encrypted_data(key_store, card_details)) .await - .map(|details| details.into()); + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt Payment method card details")?; let payment_method_metadata: Option<serde_json::Value> = req.metadata.as_ref().map(|data| data.peek()).cloned(); @@ -508,7 +515,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( payment_method_issuer: req.payment_method_issuer.clone(), scheme: req.card_network.clone(), metadata: payment_method_metadata.map(Secret::new), - payment_method_data: payment_method_data_encrypted, + payment_method_data: payment_method_data_encrypted.map(Into::into), connector_mandate_details: Some(connector_mandate_details), customer_acceptance: None, client_secret: None, @@ -527,7 +534,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( created_at: current_time, last_modified: current_time, last_used_at: current_time, - payment_method_billing_address, + payment_method_billing_address: payment_method_billing_address.map(Into::into), updated_by: None, }, merchant_account.storage_scheme, @@ -591,9 +598,14 @@ pub async fn get_client_secret_or_add_payment_method( #[cfg(feature = "payouts")] let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some(); - let payment_method_billing_address = create_encrypted_data(key_store, req.billing.clone()) + let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req + .billing + .clone() + .async_map(|billing| create_encrypted_data(key_store, billing)) .await - .map(|details| details.into()); + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt Payment method billing address")?; let connector_mandate_details = req .connector_mandate_details @@ -622,7 +634,7 @@ pub async fn get_client_secret_or_add_payment_method( Some(enums::PaymentMethodStatus::AwaitingData), None, merchant_account.storage_scheme, - payment_method_billing_address, + payment_method_billing_address.map(Into::into), None, ) .await?; @@ -793,13 +805,17 @@ pub async fn add_payment_method_data( saved_to_locker: true, }; - let updated_pmd = Some(PaymentMethodsData::Card(updated_card)); - let pm_data_encrypted = create_encrypted_data(&key_store, updated_pmd) + let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> = + create_encrypted_data( + &key_store, + PaymentMethodsData::Card(updated_card), + ) .await - .map(|details| details.into()); + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method data")?; let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate { - payment_method_data: pm_data_encrypted, + payment_method_data: Some(pm_data_encrypted.into()), status: Some(enums::PaymentMethodStatus::Active), locker_id: Some(locker_id), payment_method: req.payment_method, @@ -870,9 +886,14 @@ pub async fn add_payment_method( let merchant_id = &merchant_account.merchant_id; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; let payment_method = req.payment_method.get_required_value("payment_method")?; - let payment_method_billing_address = create_encrypted_data(key_store, req.billing.clone()) + let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req + .billing + .clone() + .async_map(|billing| create_encrypted_data(key_store, billing)) .await - .map(|details| details.into()); + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt Payment method billing address")?; let connector_mandate_details = req .connector_mandate_details @@ -1041,12 +1062,16 @@ pub async fn add_payment_method( let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) }); - let pm_data_encrypted = create_encrypted_data(key_store, updated_pmd) - .await - .map(|details| details.into()); + let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = + updated_pmd + .async_map(|updated_pmd| create_encrypted_data(key_store, updated_pmd)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method data")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: pm_data_encrypted, + payment_method_data: pm_data_encrypted.map(Into::into), }; db.update_payment_method( @@ -1086,7 +1111,7 @@ pub async fn add_payment_method( connector_mandate_details, req.network_transaction_id.clone(), merchant_account.storage_scheme, - payment_method_billing_address, + payment_method_billing_address.map(Into::into), ) .await?; @@ -1117,9 +1142,14 @@ pub async fn insert_payment_method( .card .clone() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); - let pm_data_encrypted = create_encrypted_data(key_store, pm_card_details) + + let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details + .clone() + .async_map(|pm_card| create_encrypted_data(key_store, pm_card)) .await - .map(|details| details.into()); + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method data")?; create_payment_method( db, @@ -1130,7 +1160,7 @@ pub async fn insert_payment_method( merchant_id, pm_metadata, customer_acceptance, - pm_data_encrypted, + pm_data_encrypted.map(Into::into), key_store, connector_mandate_details, None, @@ -1307,12 +1337,16 @@ pub async fn update_customer_payment_method( let updated_pmd = updated_card .as_ref() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); - let pm_data_encrypted = create_encrypted_data(&key_store, updated_pmd) + + let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd + .async_map(|updated_pmd| create_encrypted_data(&key_store, updated_pmd)) .await - .map(|details| details.into()); + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method data")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: pm_data_encrypted, + payment_method_data: pm_data_encrypted.map(Into::into), }; add_card_resp @@ -1436,7 +1470,7 @@ pub async fn add_bank_to_locker( let secret: Secret<String> = Secret::new(v.to_string()); secret }) - .async_lift(|inner| encrypt_optional(inner, key)) + .async_lift(|inner| domain::types::encrypt_optional(inner, key)) .await } .await @@ -4563,31 +4597,25 @@ pub async fn delete_payment_method( pub async fn create_encrypted_data<T>( key_store: &domain::MerchantKeyStore, - data: Option<T>, -) -> Option<Encryptable<Secret<serde_json::Value>>> + data: T, +) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>> where T: Debug + serde::Serialize, { let key = key_store.key.get_inner().peek(); - data.as_ref() - .map(Encode::encode_to_value) - .transpose() + let encoded_data = Encode::encode_to_value(&data) .change_context(errors::StorageError::SerializationFailed) - .attach_printable("Unable to convert data to a value") - .unwrap_or_else(|error| { - logger::error!(?error); - None - }) - .map(Secret::<_, masking::WithType>::new) - .async_lift(|inner| encrypt_optional(inner, key)) + .attach_printable("Unable to encode data")?; + + let secret_data = Secret::<_, masking::WithType>::new(encoded_data); + + let encrypted_data = domain::types::encrypt(secret_data, key) .await .change_context(errors::StorageError::EncryptionError) - .attach_printable("Unable to encrypt data") - .unwrap_or_else(|error| { - logger::error!(?error); - None - }) + .attach_printable("Unable to encrypt data")?; + + Ok(encrypted_data) } pub async fn list_countries_currencies_for_connector_payment_method( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 8183a01fcac..4249955c24f 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1612,8 +1612,11 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( payment_data.payment_intent.customer_details = raw_customer_details .clone() - .async_and_then(|_| async { create_encrypted_data(key_store, raw_customer_details).await }) - .await; + .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .await + .transpose() + .change_context(errors::StorageError::EncryptionError) + .attach_printable("Unable to encrypt customer details")?; let customer_id = request_customer_details .customer_id diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 771ee137474..3af3bc52190 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1222,12 +1222,20 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let billing_address = payment_data.address.get_payment_billing(); let billing_details = billing_address - .async_and_then(|_| async { create_encrypted_data(key_store, billing_address).await }) - .await; + .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt billing details")?; + let shipping_address = payment_data.address.get_shipping(); let shipping_details = shipping_address - .async_and_then(|_| async { create_encrypted_data(key_store, shipping_address).await }) - .await; + .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt shipping details")?; + let m_payment_data_payment_intent = payment_data.payment_intent.clone(); let m_customer_id = customer_id.clone(); let m_shipping_address_id = shipping_address_id.clone(); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 4e0bbec9f17..b7076d07826 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -642,10 +642,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen // details are provided in Payment Create Request let customer_details = raw_customer_details .clone() - .async_and_then(|_| async { - create_encrypted_data(key_store, raw_customer_details).await - }) - .await; + .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt customer details")?; payment_data.payment_intent = state .store @@ -1047,20 +1048,22 @@ impl PaymentCreate { let billing_details = request .billing .clone() - .async_and_then(|_| async { - create_encrypted_data(key_store, request.billing.clone()).await - }) - .await; + .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt billing details")?; // Derivation of directly supplied Shipping Address data in our Payment Create Request // Encrypting our Shipping Address Details to be stored in Payment Intent let shipping_details = request .shipping .clone() - .async_and_then(|_| async { - create_encrypted_data(key_store, request.shipping.clone()).await - }) - .await; + .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt shipping details")?; // Derivation of directly supplied Customer data in our Payment Create Request let raw_customer_details = if request.get_customer_id().is_none() @@ -1080,11 +1083,12 @@ impl PaymentCreate { }; // Encrypting our Customer Details to be stored in Payment Intent - let customer_details = if raw_customer_details.is_some() { - create_encrypted_data(key_store, raw_customer_details).await - } else { - None - }; + let customer_details = raw_customer_details + .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt customer details")?; Ok(storage::PaymentIntent { payment_id: payment_id.to_string(), diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 8af5a86d7c3..98006e574ca 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -715,22 +715,21 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let billing_details = payment_data .address .get_payment_billing() - .async_and_then(|_| async { - create_encrypted_data( - key_store, - payment_data.address.get_payment_billing().cloned(), - ) - .await - }) - .await; + .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt billing details")?; let shipping_details = payment_data .address .get_shipping() - .async_and_then(|_| async { - create_encrypted_data(key_store, payment_data.address.get_shipping().cloned()).await - }) - .await; + .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt shipping details")?; + let order_details = payment_data.payment_intent.order_details.clone(); let metadata = payment_data.payment_intent.metadata.clone(); let frm_metadata = payment_data.payment_intent.frm_metadata.clone(); diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 3fb67abd57e..b77bdb7515e 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -3,11 +3,12 @@ use std::collections::HashMap; use api_models::payment_methods::PaymentMethodsData; use common_enums::PaymentMethod; use common_utils::{ - ext_traits::{Encode, ValueExt}, + crypto::Encryptable, + ext_traits::{AsyncExt, Encode, ValueExt}, id_type, pii, }; use error_stack::{report, ResultExt}; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; use router_env::{instrument, metrics::add_attributes, tracing}; use super::helpers; @@ -15,7 +16,9 @@ use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, - mandate, payment_methods, payments, + mandate, + payment_methods::{self, cards::create_encrypted_data}, + payments, }, logger, routes::{metrics, SessionState}, @@ -64,7 +67,7 @@ pub async fn save_payment_method<FData>( key_store: &domain::MerchantKeyStore, amount: Option<i64>, currency: Option<storage_enums::Currency>, - billing_name: Option<masking::Secret<String>>, + billing_name: Option<Secret<String>>, payment_method_billing_address: Option<&api::Address>, business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)> @@ -209,18 +212,22 @@ where PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) }); - let pm_data_encrypted = - payment_methods::cards::create_encrypted_data(key_store, pm_card_details) + let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = + pm_card_details + .async_map(|pm_card| create_encrypted_data(key_store, pm_card)) .await - .map(|details| details.into()); - - let encrypted_payment_method_billing_address = - payment_methods::cards::create_encrypted_data( - key_store, - payment_method_billing_address, - ) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method data")?; + + let encrypted_payment_method_billing_address: Option< + Encryptable<Secret<serde_json::Value>>, + > = payment_method_billing_address + .async_map(|address| create_encrypted_data(key_store, address.clone())) .await - .map(|details| details.into()); + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method billing address")?; let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; @@ -311,13 +318,14 @@ where merchant_id, pm_metadata, customer_acceptance, - pm_data_encrypted, + pm_data_encrypted.map(Into::into), key_store, connector_mandate_details, None, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address, + encrypted_payment_method_billing_address + .map(Into::into), resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) @@ -411,7 +419,8 @@ where connector_mandate_details, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address, + encrypted_payment_method_billing_address + .map(Into::into), ) .await } else { @@ -506,18 +515,19 @@ where card.clone(), )) }); - let pm_data_encrypted = - payment_methods::cards::create_encrypted_data( - key_store, - updated_pmd, - ) + let pm_data_encrypted: Option< + Encryptable<Secret<serde_json::Value>>, + > = updated_pmd + .async_map(|pmd| create_encrypted_data(key_store, pmd)) .await - .map(|details| details.into()); + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method data")?; payment_methods::cards::update_payment_method_and_last_used( db, existing_pm, - pm_data_encrypted, + pm_data_encrypted.map(Into::into), merchant_account.storage_scheme, ) .await @@ -599,13 +609,13 @@ where merchant_id, pm_metadata, customer_acceptance, - pm_data_encrypted, + pm_data_encrypted.map(Into::into), key_store, connector_mandate_details, None, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address, + encrypted_payment_method_billing_address.map(Into::into), resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) @@ -877,9 +887,9 @@ pub fn update_router_data_with_payment_method_token_result<F: Clone, T>( match payment_method_token_result.payment_method_token_result { Ok(pm_token_result) => { router_data.payment_method_token = pm_token_result.map(|pm_token| { - hyperswitch_domain_models::router_data::PaymentMethodToken::Token( - masking::Secret::new(pm_token), - ) + hyperswitch_domain_models::router_data::PaymentMethodToken::Token(Secret::new( + pm_token, + )) }); true diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index fcd4f4aeeb4..2b71fedb2a3 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -452,9 +452,12 @@ pub async fn save_payout_data_to_locker( ) }); ( - cards::create_encrypted_data(key_store, Some(pm_data)) - .await - .map(|details| details.into()), + Some( + cards::create_encrypted_data(key_store, pm_data) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt customer details")?, + ), payment_method, ) } else { @@ -494,7 +497,7 @@ pub async fn save_payout_data_to_locker( &merchant_account.merchant_id, None, None, - card_details_encrypted.clone(), + card_details_encrypted.clone().map(Into::into), key_store, None, None, @@ -557,7 +560,7 @@ pub async fn save_payout_data_to_locker( // Update card's metadata in payment_methods table let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: card_details_encrypted, + payment_method_data: card_details_encrypted.map(Into::into), }; db.update_payment_method(existing_pm, pm_update, merchant_account.storage_scheme) .await diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index b3d228ced63..2a9dc1a4e9e 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -432,13 +432,13 @@ async fn store_bank_details_in_payment_methods( ); let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); - let encrypted_data = - cards::create_encrypted_data(&key_store, Some(payment_method_data)) - .await - .map(|details| details.into()) - .ok_or(ApiErrorResponse::InternalServerError)?; + let encrypted_data = cards::create_encrypted_data(&key_store, payment_method_data) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt customer details")?; + let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: Some(encrypted_data), + payment_method_data: Some(encrypted_data.into()), }; update_entries.push((pm.clone(), pm_update)); @@ -447,8 +447,8 @@ async fn store_bank_details_in_payment_methods( let encrypted_data = cards::create_encrypted_data(&key_store, Some(payment_method_data)) .await - .map(|details| details.into()) - .ok_or(ApiErrorResponse::InternalServerError)?; + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt customer details")?; let pm_id = generate_id(consts::ID_LENGTH, "pm"); let now = common_utils::date_time::now(); let pm_new = storage::PaymentMethodNew { @@ -461,7 +461,7 @@ async fn store_bank_details_in_payment_methods( payment_method_issuer: None, scheme: None, metadata: None, - payment_method_data: Some(encrypted_data), + payment_method_data: Some(encrypted_data.into()), payment_method_issuer_code: None, accepted_currency: None, token: None,
2024-07-09T08:59:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> Made `create_encrypted_data` to accept `T` and refactored the previous function into `create_encrypted_data_optional`, which takes `Option<T>`. This also improves the error propogation of this function. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### Payment create request with some random `cus_id` and `name` ``` Response should be populated like this ``` "customer_id": "id_12343", "customer": { "id": null, "name": "Light", "email": null, "phone": null, "phone_country_code": null }, ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "id_12343", "name": "Light", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
42e26e763e47706744b66cf808a158d97c31153b
juspay/hyperswitch
juspay__hyperswitch-5288
Bug: [FEATURE] [BANKOFAMERICA] Remove 3DS Flow ### Feature Description 3DS Flow is not supported on production by Bankofamerica and hence it needs to be removed. ### Possible Implementation Remove 3DS code from BOA ### 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 19bc3f9875b..daec033f6f3 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -12,7 +12,6 @@ use time::OffsetDateTime; use transformers as bankofamerica; use url::Url; -use super::utils::{PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, RouterData}; use crate::{ configs::settings, connector::{ @@ -53,8 +52,6 @@ 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 { @@ -339,33 +336,18 @@ impl } fn get_url( &self, - req: &types::SetupMandateRouterData, + _req: &types::SetupMandateRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - 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))) - } + Ok(format!("{}pts/v2/payments/", self.base_url(connectors))) } fn get_request_body( &self, req: &types::SetupMandateRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - if req.is_three_ds() && req.request.is_card() { - let connector_req = bankofamerica::BankOfAmericaAuthSetupRequest::try_from(( - &req.request.payment_method_data, - req.connector_request_reference_id.clone(), - ))?; - Ok(RequestContent::Json(Box::new(connector_req))) - } else { - let connector_req = bankofamerica::BankOfAmericaPaymentsRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } + let connector_req = bankofamerica::BankOfAmericaPaymentsRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -395,33 +377,19 @@ impl event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::SetupMandateRouterData, 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)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } else { - let response: bankofamerica::BankOfAmericaSetupMandatesResponse = res - .response - .parse_struct("BankOfAmericaSetupMandatesResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } + let response: bankofamerica::BankOfAmericaSetupMandatesResponse = res + .response + .parse_struct("BankOfAmericaSetupMandatesResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) } fn get_error_response( @@ -465,117 +433,6 @@ 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, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { - let response: bankofamerica::BankOfAmericaPreProcessingResponse = res - .response - .parse_struct("BankOfAmerica AuthEnrollmentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Bankofamerica { @@ -593,17 +450,13 @@ 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> { - 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))) - } + Ok(format!( + "{}pts/v2/payments/", + ConnectorCommon::base_url(self, connectors) + )) } fn get_request_body( @@ -617,17 +470,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.amount, req, ))?; - if req.is_three_ds() && req.request.is_card() { - let connector_req = bankofamerica::BankOfAmericaAuthSetupRequest::try_from(( - &req.request.payment_method_data, - req.connector_request_reference_id.clone(), - ))?; - 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))) - } + let connector_req = + bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -658,144 +503,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P event_builder: Option<&mut ConnectorEvent>, 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)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - 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)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } - - fn get_5xx_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: bankofamerica::BankOfAmericaServerErrorResponse = res - .response - .parse_struct("BankOfAmericaServerErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|event| event.set_response_body(&response)); - router_env::logger::info!(error_response=?response); - - 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, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaPaymentsResponse = res .response - .parse_struct("BankOfAmerica PaymentResponse") + .parse_struct("Bankofamerica PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index a82b2cc480d..c0434572ce1 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1,7 +1,6 @@ use api_models::payments; use base64::Engine; -use common_utils::{ext_traits::ValueExt, pii}; -use error_stack::ResultExt; +use common_utils::pii; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -9,13 +8,11 @@ use serde_json::Value; use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, CardIssuer, - PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, - PaymentsPreProcessingData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, + PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData, }, consts, core::errors, - services, types::{ self, api::{self, enums as api_enums}, @@ -578,28 +575,6 @@ 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: Some(bill_to), - } - } -} - impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -678,67 +653,6 @@ impl } } -impl - From<( - &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, - Option<PaymentSolution>, - &BankOfAmericaConsumerAuthValidateResponse, - )> for ProcessingInformation -{ - fn from( - (item, solution, three_ds_data): ( - &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, - Option<PaymentSolution>, - &BankOfAmericaConsumerAuthValidateResponse, - ), - ) -> Self { - let (action_list, action_token_types, authorization_options) = - if is_customer_initiated_mandate_payment(&item.router_data.request) { - ( - Some(vec![BankOfAmericaActionsList::TokenCreate]), - Some(vec![ - BankOfAmericaActionsTokenType::PaymentInstrument, - BankOfAmericaActionsTokenType::Customer, - ]), - Some(BankOfAmericaAuthorizationOptions { - initiator: Some(BankOfAmericaPaymentInitiator { - initiator_type: Some(BankOfAmericaPaymentInitiatorTypes::Customer), - credential_stored_on_file: Some(true), - stored_credential_used: None, - }), - merchant_intitiated_transaction: None, - }), - ) - } else { - (None, None, None) - }; - - let is_setup_mandate_payment = is_setup_mandate_payment(&item.router_data.request); - - let capture = if is_setup_mandate_payment { - Some(false) - } else { - Some(matches!( - item.router_data.request.capture_method, - Some(enums::CaptureMethod::Automatic) | None - )) - }; - - Self { - capture, - 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")), - } - } -} - impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> for ClientReferenceInformation { @@ -749,16 +663,6 @@ 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 From<&types::SetupMandateRouterData> for ClientReferenceInformation { fn from(item: &types::SetupMandateRouterData) -> Self { Self { @@ -894,71 +798,6 @@ pub struct Avs { code_raw: Option<String>, } -impl - TryFrom<( - &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, - domain::Card, - )> for BankOfAmericaPaymentsRequest -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (item, ccard): ( - &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, - domain::Card, - ), - ) -> Result<Self, Self::Error> { - let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; - let order_information = OrderInformationWithBill::from((item, bill_to)); - - let payment_information = PaymentInformation::try_from(&ccard)?; - 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: "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(Vec::<MerchantDefinedInformation>::foreign_from); - - Ok(Self { - processing_information, - payment_information, - order_information, - client_reference_information, - consumer_authentication_information, - merchant_defined_information, - }) - } -} - impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -1245,53 +1084,6 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct BankOfAmericaAuthSetupRequest { - payment_information: PaymentInformation, - client_reference_information: ClientReferenceInformation, -} - -impl TryFrom<(&domain::PaymentMethodData, String)> for BankOfAmericaAuthSetupRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (payment_method_data, connector_request_reference_id): (&domain::PaymentMethodData, String), - ) -> Result<Self, Self::Error> { - match payment_method_data.clone() { - domain::PaymentMethodData::Card(ccard) => { - let payment_information = PaymentInformation::try_from(&ccard)?; - let client_reference_information = ClientReferenceInformation { - code: Some(connector_request_reference_id), - }; - - Ok(Self { - payment_information, - client_reference_information, - }) - } - domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Bank Of America"), - ) - .into()) - } - } - } -} - impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -1399,39 +1191,6 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus { } } -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct BankOfAmericaConsumerAuthInformationResponse { - access_token: Secret<String>, - device_data_collection_url: Secret<String>, - reference_id: String, -} - -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ClientAuthSetupInfoResponse { - id: String, - client_reference_information: ClientReferenceInformation, - consumer_authentication_information: BankOfAmericaConsumerAuthInformationResponse, - processor_information: Option<ClientProcessorInformation>, - processing_information: Option<ProcessingInformationResponse>, - payment_account_information: Option<PaymentAccountInformation>, - payment_information: Option<PaymentInformationResponse>, - payment_insights_information: Option<PaymentInsightsInformation>, - risk_information: Option<ClientRiskInformation>, - token_information: Option<BankOfAmericaTokenInformation>, - error_information: Option<BankOfAmericaErrorInformation>, - issuer_information: Option<IssuerInformation>, - reconciliation_id: Option<String>, -} - -#[derive(Debug, Deserialize, Serialize)] -#[serde(untagged)] -pub enum BankOfAmericaAuthSetupResponse { - ClientAuthSetupInfo(Box<ClientAuthSetupInfoResponse>), - ErrorInformation(Box<BankOfAmericaErrorInformationResponse>), -} - #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BankOfAmericaPaymentsResponse { @@ -1745,533 +1504,6 @@ fn get_payment_response( } } -impl<F, T> - TryFrom< - types::ResponseRouterData< - F, - BankOfAmericaAuthSetupResponse, - T, - types::PaymentsResponseData, - >, - > for types::RouterData<F, T, types::PaymentsResponseData> -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: types::ResponseRouterData< - F, - BankOfAmericaAuthSetupResponse, - T, - 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 - .expose(), - ddc_url: info_response - .consumer_authentication_information - .device_data_collection_url - .expose(), - 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, - charge_id: None, - }), - ..item.data - }), - BankOfAmericaAuthSetupResponse::ErrorInformation(error_response) => { - let detailed_error_info = - error_response - .error_information - .to_owned() - .details - .map(|error_details| { - error_details - .iter() - .map(|details| format!("{} : {}", details.field, details.reason)) - .collect::<Vec<_>>() - .join(", ") - }); - - let reason = get_error_reason( - error_response.error_information.message, - detailed_error_info, - None, - ); - - Ok(Self { - response: Err(types::ErrorResponse { - code: error_response - .error_information - .reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_response - .error_information - .reason - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - 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(Box<BankOfAmericaAuthEnrollmentRequest>), - AuthValidate(Box<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 { - domain::PaymentMethodData::Card(ccard) => PaymentInformation::try_from(&ccard), - domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), - ) - .into()) - } - }?; - - 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_optional_billing(), email)?; - let order_information = OrderInformationWithBill { - amount_details, - bill_to: Some(bill_to), - }; - Ok(Self::AuthEnrollment(Box::new( - 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(Box::new( - 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 { - domain::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), - domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), - ) - .into()) - } - } - } -} - -#[derive(Debug, Deserialize, Serialize)] -#[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<Secret<String>>, - xid: Option<String>, - specification_version: Option<String>, - directory_server_transaction_id: Option<Secret<String>>, - indicator: Option<String>, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct BankOfAmericaThreeDSMetadata { - three_ds_data: BankOfAmericaConsumerAuthValidateResponse, -} - -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse { - access_token: Option<Secret<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, Serialize)] -#[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, Serialize)] -#[serde(untagged)] -pub enum BankOfAmericaPreProcessingResponse { - ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), - ErrorInformation(Box<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::foreign_from(( - &info_response.error_information, - &risk_info, - Some(status), - 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 - .map(|access_token| access_token.expose()), - 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, - ) - .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, - charge_id: None, - }), - ..item.data - }) - } - } - BankOfAmericaPreProcessingResponse::ErrorInformation(error_response) => { - let response = Err(types::ErrorResponse::foreign_from(( - &*error_response, - item.http_code, - ))); - 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()? - || is_setup_mandate_payment(&item.data.request), - )); - let response = get_payment_response((&info_response, status, item.http_code)); - let connector_response = match item.data.payment_method { - common_enums::PaymentMethod::Card => info_response - .processor_information - .as_ref() - .and_then(|processor_information| { - info_response - .consumer_authentication_information - .as_ref() - .map(|consumer_auth_information| { - types::AdditionalPaymentMethodConnectorResponse::foreign_from(( - processor_information, - consumer_auth_information, - )) - }) - }) - .map(types::ConnectorResponseData::with_additional_payment_method_data), - common_enums::PaymentMethod::CardRedirect - | common_enums::PaymentMethod::PayLater - | common_enums::PaymentMethod::Wallet - | common_enums::PaymentMethod::BankRedirect - | common_enums::PaymentMethod::BankTransfer - | common_enums::PaymentMethod::Crypto - | common_enums::PaymentMethod::BankDebit - | common_enums::PaymentMethod::Reward - | common_enums::PaymentMethod::RealTimePayment - | common_enums::PaymentMethod::Upi - | common_enums::PaymentMethod::Voucher - | common_enums::PaymentMethod::GiftCard => None, - }; - - Ok(Self { - status, - response, - connector_response, - ..item.data - }) - } - BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { - Ok(Self::foreign_from(( - &*error_response.clone(), - item, - Some(enums::AttemptStatus::Failure), - ))) - } - } - } -} - impl<F> TryFrom< types::ResponseRouterData< @@ -3318,17 +2550,6 @@ fn get_commerce_indicator(network: Option<String>) -> String { .to_string() } -fn is_setup_mandate_payment(item: &types::CompleteAuthorizeData) -> bool { - matches!(item.amount, 0) && is_customer_initiated_mandate_payment(item) -} - -fn is_customer_initiated_mandate_payment(item: &types::CompleteAuthorizeData) -> bool { - item.setup_future_usage.map_or(false, |future_usage| { - matches!(future_usage, common_enums::FutureUsage::OffSession) - }) - // add check for customer_acceptance -} - pub fn get_error_reason( error_info: Option<String>, detailed_error_info: Option<String>, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 18e62b9c1c8..55edce1b856 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1975,8 +1975,7 @@ where router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) - } else if (connector.connector_name == router_types::Connector::Cybersource - || connector.connector_name == router_types::Connector::Bankofamerica) + } else if connector.connector_name == router_types::Connector::Cybersource && 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 fec9471ea99..60f14dd3995 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -166,6 +166,7 @@ default_imp_for_complete_authorize!( connector::Aci, connector::Adyen, connector::Bamboraapac, + connector::Bankofamerica, connector::Billwerk, connector::Bitpay, connector::Boku, @@ -987,6 +988,7 @@ default_imp_for_pre_processing_steps!( connector::Authorizedotnet, connector::Bambora, connector::Bamboraapac, + connector::Bankofamerica, connector::Billwerk, connector::Bitpay, connector::Bluesnap,
2024-07-11T10:23:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Cards 3DS Flow is not supported on production by Bankofamerica and hence it is removed. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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/5288 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 3DS Flow is not supported on production by Bankofamerica hence it is removed. 3DS payments will now go through normal Non-3DS flow. Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mF5ApaF7qylFyewcvRbsOVw9bhOUy2ufhC8MutbWQvLwNWWqX7CZGDPf5SnZ6KRE' \ --data-raw '{ "amount": 999, "currency": "USD", "confirm": true, "customer_id": "hkfewkhefwdwfkhj", "email": "guest@deepankjnshgkhju.com", "return_url": "https://google.com", "authentication_type": "three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "05", "card_exp_year": "25", "card_cvc": "123" } }, "billing": { "address": { "line1": "eqnkl", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "IN", "first_name": "John", "last_name": "Bond" } } }' ``` Response: ``` { "payment_id": "pay_cwUGBO1EUp1YSnICJnGt", "merchant_id": "merchant_1718024306", "status": "succeeded", "amount": 999, "net_amount": 999, "amount_capturable": 0, "amount_received": 999, "connector": "bankofamerica", "client_secret": "pay_cwUGBO1EUp1YSnICJnGt_secret_58yq6aN6TMIx3rawYRru", "created": "2024-07-11T11:01:04.937Z", "currency": "USD", "customer_id": "hkfewkhefwdwfkhj", "customer": { "id": "hkfewkhefwdwfkhj", "name": null, "email": "guest@deepankjnshgkhju.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "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_extended_bin": null, "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": null, "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" }, "approval_code": "831000", "consumer_authentication_response": { "code": "2", "codeRaw": "2" }, "cavv": null, "eci": null, "eci_raw": null }, "authentication_data": { "retrieval_reference_number": "419311106891", "acs_transaction_id": null, "system_trace_audit_number": "106891" } }, "billing": null }, "payment_token": "token_M45bEnvOf2GPLMysWnOr", "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "IN", "line1": "eqnkl", "line2": null, "line3": null, "zip": "94122", "state": "CA", "first_name": "John", "last_name": "Bond" }, "phone": null, "email": null }, "order_details": null, "email": "guest@deepankjnshgkhju.com", "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "hkfewkhefwdwfkhj", "created_at": 1720695664, "expires": 1720699264, "secret": "epk_76f83d509ad3425db0f6f724459079ee" }, "manual_retry_allowed": false, "connector_transaction_id": "7206956666866029204951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_cwUGBO1EUp1YSnICJnGt_1", "payment_link": null, "profile_id": "pro_sjoiFN7MPB9SdG5Zr0iT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_QxbSnL7xEEr3Wc2sODHD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-11T11:16:04.937Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-11T11:01:07.583Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
3312e787f9873d10114e6a4ca78a0c3714ab2b1c
juspay/hyperswitch
juspay__hyperswitch-5259
Bug: [BUG] Retrieve Payment Id Throwing 4xx ### Bug Description For MIT transaction, using non MIT payment method Ids, throwing 400. When retreive this payment, it is throwing 422. ### Expected Behavior https://api-reference.hyperswitch.io/api-reference/payments/payments--retrieve ### Actual Behavior { "error": { "type": "invalid_request", "message": "no customer id provided for the payment", "code": "IR_23" } } ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Disable recurring from Adyen dashboard 2. Create a recurring payment in Adyen via hyperswitch 3. Hyperswitch sends a successful transaction and payment method id 4. Use the payment_method_id, to do MIT transaction. It fails, genuine fails 5. Try to retrieve the payment. It fails. this is the problem ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes If yes, please provide the value of the `x-request-id` response header to help us debug your issue. `x-request-id : 01909742-36b7-7e91-9e62-6f684418fb1c` ### 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/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 97fc20d9444..d63ac8a030f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -518,6 +518,139 @@ pub struct PaymentsRequest { pub merchant_order_reference_id: Option<String>, } +/// Checks if the inner values of two options are equal +/// Returns true if values are not equal, returns false in other cases +fn are_optional_values_invalid<T: PartialEq>( + first_option: Option<&T>, + second_option: Option<&T>, +) -> bool { + match (first_option, second_option) { + (Some(first_option), Some(second_option)) => first_option != second_option, + _ => false, + } +} + +impl PaymentsRequest { + /// Get the customer id + /// + /// First check the id for `customer.id` + /// If not present, check for `customer_id` at the root level + pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { + self.customer_id + .as_ref() + .or(self.customer.as_ref().map(|customer| &customer.id)) + } + + /// Checks if the customer details are passed in both places + /// If they are passed in both places, check for both the values to be equal + /// Or else, return the field which has inconsistent data + pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { + if let Some(CustomerDetails { + id, + name, + email, + phone, + phone_country_code, + }) = self.customer.as_ref() + { + let invalid_fields = [ + are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) + .then_some("customer_id and customer.id"), + are_optional_values_invalid(self.email.as_ref(), email.as_ref()) + .then_some("email and customer.email"), + are_optional_values_invalid(self.name.as_ref(), name.as_ref()) + .then_some("name and customer.name"), + are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) + .then_some("phone and customer.phone"), + are_optional_values_invalid( + self.phone_country_code.as_ref(), + phone_country_code.as_ref(), + ) + .then_some("phone_country_code and customer.phone_country_code"), + ] + .into_iter() + .flatten() + .collect::<Vec<_>>(); + + if invalid_fields.is_empty() { + None + } else { + Some(invalid_fields) + } + } else { + None + } + } +} + +#[cfg(test)] +mod payments_request_test { + use common_utils::generate_customer_id_of_default_length; + + use super::*; + + #[test] + fn test_valid_case_where_customer_details_are_passed_only_once() { + let customer_id = generate_customer_id_of_default_length(); + let payments_request = PaymentsRequest { + customer_id: Some(customer_id), + ..Default::default() + }; + + assert!(payments_request + .validate_customer_details_in_request() + .is_none()); + } + + #[test] + fn test_valid_case_where_customer_id_is_passed_in_both_places() { + let customer_id = generate_customer_id_of_default_length(); + + let customer_object = CustomerDetails { + id: customer_id.clone(), + name: None, + email: None, + phone: None, + phone_country_code: None, + }; + + let payments_request = PaymentsRequest { + customer_id: Some(customer_id), + customer: Some(customer_object), + ..Default::default() + }; + + assert!(payments_request + .validate_customer_details_in_request() + .is_none()); + } + + #[test] + fn test_invalid_case_where_customer_id_is_passed_in_both_places() { + let customer_id = generate_customer_id_of_default_length(); + let another_customer_id = generate_customer_id_of_default_length(); + + let customer_object = CustomerDetails { + id: customer_id.clone(), + name: None, + email: None, + phone: None, + phone_country_code: None, + }; + + let payments_request = PaymentsRequest { + customer_id: Some(another_customer_id), + customer: Some(customer_object), + ..Default::default() + }; + + assert_eq!( + payments_request.validate_customer_details_in_request(), + Some(vec!["customer_id and customer.id"]) + ); + } +} + /// Fee information to be charged on the payment being collected #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index c19480f1d56..a19db991bf3 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -451,7 +451,7 @@ pub async fn get_token_pm_type_mandate_details( merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, payment_method_id: Option<String>, - customer_id: &Option<id_type::CustomerId>, + payment_intent_customer_id: Option<&id_type::CustomerId>, ) -> RouterResult<MandateGenericData> { let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from); let ( @@ -505,14 +505,15 @@ pub async fn get_token_pm_type_mandate_details( .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, )?; - let customer_id = get_customer_id_from_payment_request(request) + let customer_id = request + .get_customer_id() .get_required_value("customer_id")?; verify_mandate_details_for_recurring_payments( &payment_method_info.merchant_id, &merchant_account.merchant_id, &payment_method_info.customer_id, - &customer_id, + customer_id, )?; ( @@ -552,10 +553,9 @@ pub async fn get_token_pm_type_mandate_details( || request.payment_method_type == Some(api_models::enums::PaymentMethodType::GooglePay) { - let payment_request_customer_id = - get_customer_id_from_payment_request(request); + let payment_request_customer_id = request.get_customer_id(); if let Some(customer_id) = - &payment_request_customer_id.or(customer_id.clone()) + payment_request_customer_id.or(payment_intent_customer_id) { let customer_saved_pm_option = match state .store @@ -711,10 +711,10 @@ pub async fn get_token_for_recurring_mandate( .map(|pi| pi.amount.get_amount_as_i64()); let original_payment_authorized_currency = original_payment_intent.clone().and_then(|pi| pi.currency); - let customer = get_customer_id_from_payment_request(req).get_required_value("customer_id")?; + let customer = req.get_customer_id().get_required_value("customer_id")?; let payment_method_id = { - if mandate.customer_id != customer { + if &mandate.customer_id != customer { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "customer_id must match mandate customer_id".into() }))? @@ -1453,25 +1453,6 @@ pub async fn get_customer_from_details<F: Clone>( } } -// Checks if the inner values of two options are not equal and throws appropriate error -fn validate_options_for_inequality<T: PartialEq>( - first_option: Option<&T>, - second_option: Option<&T>, - field_name: &str, -) -> Result<(), errors::ApiErrorResponse> { - fp_utils::when( - first_option - .zip(second_option) - .map(|(value1, value2)| value1 != value2) - .unwrap_or(false), - || { - Err(errors::ApiErrorResponse::PreconditionFailed { - message: format!("The field name `{field_name}` sent in both places is ambiguous"), - }) - }, - ) -} - pub fn validate_max_amount( amount: api_models::payments::Amount, ) -> CustomResult<(), errors::ApiErrorResponse> { @@ -1490,44 +1471,21 @@ pub fn validate_max_amount( } } -// Checks if the customer details are passed in both places -// If so, raise an error -pub fn validate_customer_details_in_request( +/// Check whether the customer information that is sent in the root of payments request +/// and in the customer object are same, if the values mismatch return an error +pub fn validate_customer_information( request: &api_models::payments::PaymentsRequest, -) -> Result<(), errors::ApiErrorResponse> { - if let Some(customer_details) = request.customer.as_ref() { - validate_options_for_inequality( - request.customer_id.as_ref(), - Some(&customer_details.id), - "customer_id", - )?; - - validate_options_for_inequality( - request.email.as_ref(), - customer_details.email.as_ref(), - "email", - )?; - - validate_options_for_inequality( - request.name.as_ref(), - customer_details.name.as_ref(), - "name", - )?; - - validate_options_for_inequality( - request.phone.as_ref(), - customer_details.phone.as_ref(), - "phone", - )?; - - validate_options_for_inequality( - request.phone_country_code.as_ref(), - customer_details.phone_country_code.as_ref(), - "phone_country_code", - )?; +) -> RouterResult<()> { + if let Some(mismatched_fields) = request.validate_customer_details_in_request() { + let mismatched_fields = mismatched_fields.join(", "); + Err(errors::ApiErrorResponse::PreconditionFailed { + message: format!( + "The field names `{mismatched_fields}` sent in both places is ambiguous" + ), + })? + } else { + Ok(()) } - - Ok(()) } /// Get the customer details from customer field if present @@ -1536,12 +1494,7 @@ pub fn validate_customer_details_in_request( pub fn get_customer_details_from_request( request: &api_models::payments::PaymentsRequest, ) -> CustomerDetails { - let customer_id = request - .customer - .as_ref() - .map(|customer_details| &customer_details.id) - .or(request.customer_id.as_ref()) - .map(ToOwned::to_owned); + let customer_id = request.get_customer_id().map(ToOwned::to_owned); let customer_name = request .customer @@ -1576,16 +1529,6 @@ pub fn get_customer_details_from_request( } } -fn get_customer_id_from_payment_request( - request: &api_models::payments::PaymentsRequest, -) -> Option<id_type::CustomerId> { - request - .customer - .as_ref() - .map(|customer| customer.id.clone()) - .or(request.customer_id.clone()) -} - pub async fn get_connector_default( _state: &SessionState, request_connector: Option<serde_json::Value>, @@ -4079,8 +4022,8 @@ pub fn validate_customer_access( auth_flow: services::AuthFlow, request: &api::PaymentsRequest, ) -> Result<(), errors::ApiErrorResponse> { - if auth_flow == services::AuthFlow::Client && request.customer_id.is_some() { - let is_same_customer = request.customer_id == payment_intent.customer_id; + if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() { + let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref(); if !is_same_customer { Err(errors::ApiErrorResponse::GenericUnauthorized { message: "Unauthorised access to update customer".to_string(), diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 060acf51549..9c48df1dd53 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -126,7 +126,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co merchant_account, key_store, payment_attempt.payment_method_id.clone(), - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; let customer_acceptance: Option<CustomerAcceptance> = request @@ -188,12 +188,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); + let customer_id = payment_intent + .customer_id + .as_ref() + .or(request.get_customer_id()) + .cloned(); + helpers::validate_customer_id_mandatory_cases( request.setup_future_usage.is_some(), - payment_intent - .customer_id - .as_ref() - .or(request.customer_id.as_ref()), + customer_id.as_ref(), )?; let shipping_address = helpers::create_or_update_address_for_payment_by_request( @@ -337,7 +340,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co }; let customer_details = Some(CustomerDetails { - customer_id: request.customer_id.clone(), + customer_id, name: request.name.clone(), email: request.email.clone(), phone: request.phone.clone(), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 9fe28c38106..771ee137474 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -508,7 +508,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &m_merchant_account, &m_key_store, None, - &payment_intent_customer_id, + payment_intent_customer_id.as_ref(), ) .await } @@ -1353,7 +1353,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - helpers::validate_customer_details_in_request(request)?; + helpers::validate_customer_information(request)?; + if let Some(amount) = request.amount { helpers::validate_max_amount(amount)?; } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 4204972411a..4e0bbec9f17 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -136,7 +136,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa merchant_account, merchant_key_store, None, - &request.customer_id, + None, ) .await?; @@ -684,7 +684,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - helpers::validate_customer_details_in_request(request)?; + helpers::validate_customer_information(request)?; + if let Some(amount) = request.amount { helpers::validate_max_amount(amount)?; } @@ -749,11 +750,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate helpers::validate_customer_id_mandatory_cases( request.setup_future_usage.is_some(), - request - .customer - .as_ref() - .map(|customer| &customer.id) - .or(request.customer_id.as_ref()), + request.get_customer_id(), )?; } @@ -1066,7 +1063,7 @@ impl PaymentCreate { .await; // Derivation of directly supplied Customer data in our Payment Create Request - let raw_customer_details = if request.customer_id.is_none() + let raw_customer_details = if request.get_customer_id().is_none() && (request.name.is_some() || request.email.is_some() || request.phone.is_some() @@ -1115,7 +1112,7 @@ impl PaymentCreate { ), order_details, amount_captured: None, - customer_id: None, + customer_id: request.get_customer_id().cloned(), connector_id: None, allowed_payment_method_types, connector_metadata, @@ -1149,10 +1146,10 @@ impl PaymentCreate { state: &SessionState, merchant_account: &domain::MerchantAccount, ) -> Option<ephemeral_key::EphemeralKey> { - match request.customer_id.clone() { + match request.get_customer_id() { Some(customer_id) => helpers::make_ephemeral_key( state.clone(), - customer_id, + customer_id.clone(), merchant_account.merchant_id.clone(), ) .await diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 0bccd409cac..8af5a86d7c3 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -151,7 +151,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa merchant_account, key_store, None, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?; @@ -807,7 +807,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - helpers::validate_customer_details_in_request(request)?; + helpers::validate_customer_information(request)?; + if let Some(amount) = request.amount { helpers::validate_max_amount(amount)?; }
2024-07-09T17:16:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> In case we receive a 4xx when creating the payment before calling the connector, we do not save the `customer_id` in payment intent. This PR fixes it This PR also includes changes to ensure that `customer_id` is always taken from both the places in the PaymentsRequest. The root `customer_id` and `customer.id` field. <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a merchant account ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "merchant_id": "merchant_1720593206" }' ``` - Create an api key ```bash curl --location 'http://localhost:8080/api_keys/merchant_1720593134' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2038-01-19T03:14:08.000Z" }' ``` - Create a payment ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RMV9h1z6QVqWHW9B7LBRl6peSokwQ7go96pfAjehuGZDGiwlenKAbgtyqUlXny9J' \ --data '{ "amount": 0, "payment_id": "pay_1720593248", "customer_id": "cus_123", "currency": "USD", "confirm": true, "payment_type": "setup_mandate", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } }' ``` Fails with the error message ```json { "error": { "type": "invalid_request", "message": "No eligible connector was found for the current payment method configuration", "code": "HE_04" } } ``` - Check in the database whether `customer_id` is updated <img width="1014" alt="image" src="https://github.com/juspay/hyperswitch/assets/48803246/a83fce74-2aa9-4670-b074-d1ea77bb3e14"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
fdac31324110ebe20ba56dd60cfe8c41dbd309a4
juspay/hyperswitch
juspay__hyperswitch-5256
Bug: refactor: fix auth select flow for default users When no `id` is passed to auth_select request is should consider default case for user authentication method and give `totp` as the next SPT.
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 49993f3873a..2abcb5ea78b 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -27,6 +27,7 @@ use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; use crate::services::email::types as email_types; use crate::{ consts, + db::domain::user_authentication_method::DEFAULT_USER_AUTH_METHOD, routes::{app::ReqState, SessionState}, services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse}, types::{domain, transformers::ForeignInto}, @@ -2306,38 +2307,25 @@ pub async fn terminate_auth_select( .change_context(UserErrors::InternalServerError)? .into(); - if let Some(id) = &req.id { - let user_authentication_method = state + let user_authentication_method = if let Some(id) = &req.id { + state .store .get_user_authentication_method_by_id(id) .await - .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; - - let current_flow = - domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; - let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; - - // Skip SSO if continue with password(TOTP) - if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) - && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) - { - next_flow = next_flow.skip(user_from_db, &state).await?; - } - let token = next_flow.get_token(&state).await?; - - return auth::cookies::set_cookie_response( - user_api::TokenResponse { - token: token.clone(), - token_type: next_flow.get_flow().into(), - }, - token, - ); - } + .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)? + } else { + DEFAULT_USER_AUTH_METHOD.clone() + }; - // Giving totp token for hyperswtich users when no id is present in the request body let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; - next_flow = next_flow.skip(user_from_db, &state).await?; + + // Skip SSO if continue with password(TOTP) + if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) + && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) + { + next_flow = next_flow.skip(user_from_db, &state).await?; + } let token = next_flow.get_token(&state).await?; auth::cookies::set_cookie_response( diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 4c48c21204b..d5100c89c19 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -37,6 +37,7 @@ use crate::{ pub mod dashboard_metadata; pub mod decision_manager; pub use decision_manager::*; +pub mod user_authentication_method; use super::{types as domain_types, UserKeyStore}; diff --git a/crates/router/src/types/domain/user/user_authentication_method.rs b/crates/router/src/types/domain/user/user_authentication_method.rs new file mode 100644 index 00000000000..570e144961a --- /dev/null +++ b/crates/router/src/types/domain/user/user_authentication_method.rs @@ -0,0 +1,17 @@ +use common_enums::{Owner, UserAuthType}; +use diesel_models::UserAuthenticationMethod; +use once_cell::sync::Lazy; + +pub static DEFAULT_USER_AUTH_METHOD: Lazy<UserAuthenticationMethod> = + Lazy::new(|| UserAuthenticationMethod { + id: String::from("hyperswitch_default"), + auth_id: String::from("hyperswitch"), + owner_id: String::from("hyperswitch"), + owner_type: Owner::Tenant, + auth_type: UserAuthType::Password, + private_config: None, + public_config: None, + allow_signup: true, + created_at: common_utils::date_time::now(), + last_modified_at: common_utils::date_time::now(), + });
2024-07-09T09:59:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Populated the User Authentication Method data statically for default users - Auth select should give next flow as `totp` when no `id` is passed ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes #5256 ## How did you test it? For no id present in the reqeust: ``` curl --location 'http://localhost:8080/user/auth/select' \ --header 'Authorization: Bearer SPT' \ --header 'Content-Type: application/json' \ --data '{ }` ``` Respnse: ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJhY2NlcHRfaW52aXRhdGlvbl9mcm9tX2VtYWlsIiwicGF0aCI6WyJhdXRoX3NlbGVjdCJdLCJleHAiOjE3MjA2OTE2OTl9.5-tVDAdKytWrzc17N77uMARuJJqyX0OohT-LybY-xn4", "token_type": "totp" } ``` For id which is not present in the user authentication method ``` curl --location 'http://localhost:8080/user/auth/select' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6ImF1dGhfc2VsZWN0Iiwib3JpZ2luIjoiYWNjZXB0X2ludml0YXRpb25fZnJvbV9lbWFpbCIsInBhdGgiOltdLCJleHAiOjE4MTk1ODQ1NDN9._vo2f5SpbKFcpNipvLqbJTsEJ5YwSdL__3Igg7yU4-4' \ --header 'Content-Type: application/json' \ --data '{ "id": "not_present" }` ``` Respnse will be bad request: ``` { "error": { "type": "invalid_request", "message": "Invalid user auth method operation", "code": "UR_44" } } ``` For Some id for which user auth method is present the in response we will get token type accodingly: ``` curl --location 'http://localhost:8080/user/auth/select' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6ImF1dGhfc2VsZWN0Iiwib3JpZ2luIjoiYWNjZXB0X2ludml0YXRpb25fZnJvbV9lbWFpbCIsInBhdGgiOltdLCJleHAiOjE4MTk1ODQ1NDN9._vo2f5SpbKFcpNipvLqbJTsEJ5YwSdL__3Igg7yU4-4' \ --header 'Content-Type: application/json' \ --data '{ "id": "f20742d2-f1b8-4dad-8b2d-cf8fe6d457eb" } ' ``` Response: ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6InNzbyIsIm9yaWdpbiI6ImFjY2VwdF9pbnZpdGF0aW9uX2Zyb21fZW1haWwiLCJwYXRoIjpbImF1dGhfc2VsZWN0Il0sImV4cCI6MTcyMDY5MTg3Nn0.SNmkULnpkYNtxuyJ3BE7d1J7fzVZx0pg1LTsBFwFx0o", "token_type": "sso" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d6b9151e9edae17e06234c8958170bf38ff060bc
juspay/hyperswitch
juspay__hyperswitch-5285
Bug: feat(connector): [WELLS FARGO] add Connector Template Code Add Wellsfargo Connector Template Code
diff --git a/config/config.example.toml b/config/config.example.toml index aa98c0533e3..941a315aaee 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -251,6 +251,7 @@ trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" volt.base_url = "https://api.sandbox.volt.io/" +wellsfargo.base_url = "https://apitest.cybersource.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index c11fb1b8904..7c946f8209b 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -89,6 +89,7 @@ trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" volt.base_url = "https://api.sandbox.volt.io/" +wellsfargo.base_url = "https://apitest.cybersource.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 478c77bdd56..4630b969224 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -93,6 +93,7 @@ trustpay.base_url = "https://tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://gateway.transit-pass.com/" volt.base_url = "https://api.volt.io/" +wellsfargo.base_url = "https://api.cybersource.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index ad93982225b..5fb7bfe0d68 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -93,6 +93,7 @@ trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" volt.base_url = "https://api.sandbox.volt.io/" +wellsfargo.base_url = "https://apitest.cybersource.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" diff --git a/config/development.toml b/config/development.toml index 49bc7756cc0..48aa82b07a2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -152,6 +152,7 @@ cards = [ "trustpay", "tsys", "volt", + "wellsfargo", "wise", "worldline", "worldpay", @@ -248,6 +249,7 @@ worldpay.base_url = "https://try.access.worldpay.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" volt.base_url = "https://api.sandbox.volt.io/" +wellsfargo.base_url = "https://apitest.cybersource.com/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" zen.base_url = "https://api.zen-test.com/" zen.secondary_base_url = "https://secure.zen-test.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 7f89acd01e2..61fdf86e457 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -180,6 +180,7 @@ trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" volt.base_url = "https://api.sandbox.volt.io/" +wellsfargo.base_url = "https://apitest.cybersource.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" @@ -251,6 +252,7 @@ cards = [ "trustpay", "tsys", "volt", + "wellsfargo", "wise", "worldline", "worldpay", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 28a1296468a..79cb60da2d7 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -132,6 +132,7 @@ pub enum Connector { // Tsys, Tsys, Volt, + // Wellsfargo, Wise, Worldline, Worldpay, @@ -250,6 +251,7 @@ impl Connector { | Self::Trustpay | Self::Tsys | Self::Volt + // | Self::Wellsfargo | Self::Wise | Self::Worldline | Self::Worldpay diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 16f877c4c33..a9eec76cc13 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -247,6 +247,7 @@ pub enum RoutableConnectors { // Tsys, Tsys, Volt, + // Wellsfargo, Wise, Worldline, Worldpay, diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index 3072a952b15..7634c006a7b 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -77,6 +77,7 @@ pub struct Connectors { pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub volt: ConnectorParams, + pub wellsfargo: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 85f51bcc110..3a938d0ba60 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -63,6 +63,7 @@ pub mod trustpay; pub mod tsys; pub mod utils; pub mod volt; +pub mod wellsfargo; pub mod wise; pub mod worldline; pub mod worldpay; @@ -85,6 +86,6 @@ pub use self::{ paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, square::Square, stax::Stax, stripe::Stripe, threedsecureio::Threedsecureio, - trustpay::Trustpay, tsys::Tsys, volt::Volt, wise::Wise, worldline::Worldline, - worldpay::Worldpay, zen::Zen, zsl::Zsl, + trustpay::Trustpay, tsys::Tsys, volt::Volt, wellsfargo::Wellsfargo, wise::Wise, + worldline::Worldline, worldpay::Worldpay, zen::Zen, zsl::Zsl, }; diff --git a/crates/router/src/connector/wellsfargo.rs b/crates/router/src/connector/wellsfargo.rs new file mode 100644 index 00000000000..51ff838afd3 --- /dev/null +++ b/crates/router/src/connector/wellsfargo.rs @@ -0,0 +1,579 @@ +pub mod transformers; + +use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}; +use error_stack::{report, ResultExt}; +use masking::ExposeInterface; +use transformers as wellsfargo; + +use super::utils::{self as connector_utils}; +use crate::{ + configs::settings, + core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, + headers, + services::{ + self, + request::{self, Mask}, + ConnectorIntegration, ConnectorValidation, + }, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, RequestContent, Response, + }, + utils::BytesExt, +}; + +#[derive(Clone)] +pub struct Wellsfargo { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Wellsfargo { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Wellsfargo {} +impl api::PaymentSession for Wellsfargo {} +impl api::ConnectorAccessToken for Wellsfargo {} +impl api::MandateSetup for Wellsfargo {} +impl api::PaymentAuthorize for Wellsfargo {} +impl api::PaymentSync for Wellsfargo {} +impl api::PaymentCapture for Wellsfargo {} +impl api::PaymentVoid for Wellsfargo {} +impl api::Refund for Wellsfargo {} +impl api::RefundExecute for Wellsfargo {} +impl api::RefundSync for Wellsfargo {} +impl api::PaymentToken for Wellsfargo {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Wellsfargo +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wellsfargo +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Wellsfargo { + fn id(&self) -> &'static str { + "wellsfargo" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + // TODO! Check connector documentation, on which unit they are processing the currency. + // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, + // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.wellsfargo.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let auth = wellsfargo::WellsfargoAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.expose().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: wellsfargo::WellsfargoErrorResponse = res + .response + .parse_struct("WellsfargoErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + attempt_status: None, + connector_transaction_id: None, + }) + } +} + +impl ConnectorValidation for Wellsfargo { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Wellsfargo +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Wellsfargo +{ +} + +impl + ConnectorIntegration< + api::SetupMandate, + types::SetupMandateRequestData, + types::PaymentsResponseData, + > for Wellsfargo +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Wellsfargo +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + 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::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); + let connector_req = + wellsfargo::WellsfargoPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: wellsfargo::WellsfargoPaymentsResponse = res + .response + .parse_struct("Wellsfargo PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Wellsfargo +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + 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::PaymentsSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response: wellsfargo::WellsfargoPaymentsResponse = res + .response + .parse_struct("wellsfargo PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Wellsfargo +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + 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::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: wellsfargo::WellsfargoPaymentsResponse = res + .response + .parse_struct("Wellsfargo PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Wellsfargo +{ +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Wellsfargo +{ + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + 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::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = wellsfargo::WellsfargoRouterData::from((refund_amount, req)); + let connector_req = wellsfargo::WellsfargoRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + let response: wellsfargo::RefundResponse = res + .response + .parse_struct("wellsfargo RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Wellsfargo +{ + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + 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::RefundSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + let response: wellsfargo::RefundResponse = res + .response + .parse_struct("wellsfargo RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Wellsfargo { + fn get_webhook_object_reference_id( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs new file mode 100644 index 00000000000..d0a1bb41402 --- /dev/null +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -0,0 +1,234 @@ +use common_utils::types::StringMinorUnit; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + connector::utils::PaymentsAuthorizeRequestData, + core::errors, + types::{self, api, domain, storage::enums}, +}; + +//TODO: Fill the struct with respective fields +pub struct WellsfargoRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for WellsfargoRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct WellsfargoPaymentsRequest { + amount: StringMinorUnit, + card: WellsfargoCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct WellsfargoCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>> + for WellsfargoPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + domain::PaymentMethodData::Card(req_card) => { + let card = WellsfargoCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct WellsfargoAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for WellsfargoAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum WellsfargoPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<WellsfargoPaymentStatus> for enums::AttemptStatus { + fn from(item: WellsfargoPaymentStatus) -> Self { + match item { + WellsfargoPaymentStatus::Succeeded => Self::Charged, + WellsfargoPaymentStatus::Failed => Self::Failure, + WellsfargoPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct WellsfargoPaymentsResponse { + status: WellsfargoPaymentStatus, + id: String, +} + +impl<F, T> + TryFrom< + types::ResponseRouterData<F, WellsfargoPaymentsResponse, T, types::PaymentsResponseData>, + > for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + WellsfargoPaymentsResponse, + 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), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct WellsfargoRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&WellsfargoRouterData<&types::RefundsRouterData<F>>> for WellsfargoRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &WellsfargoRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct WellsfargoErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 607c478eb43..ca73a07de3c 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2639,6 +2639,10 @@ pub(crate) fn validate_auth_and_metadata_type_with_connector( volt::transformers::VoltAuthType::try_from(val)?; Ok(()) } + // api_enums::Connector::Wellsfargo => { + // wellsfargo::transformers::WellsfargoAuthType::try_from(val)?; + // Ok(()) + // } api_enums::Connector::Wise => { wise::transformers::WiseAuthType::try_from(val)?; Ok(()) diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs index 277326889d3..e86f94dc251 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -695,6 +695,7 @@ default_imp_for_new_connector_integration_payment!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -781,6 +782,7 @@ default_imp_for_new_connector_integration_refund!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -862,6 +864,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -965,6 +968,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1050,6 +1054,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1119,6 +1124,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1215,6 +1221,7 @@ default_imp_for_new_connector_integration_file_upload!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1293,6 +1300,7 @@ default_imp_for_new_connector_integration_payouts!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1381,6 +1389,7 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1469,6 +1478,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1557,6 +1567,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1645,6 +1656,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1733,6 +1745,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1821,6 +1834,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1909,6 +1923,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1997,6 +2012,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2083,6 +2099,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2161,6 +2178,7 @@ default_imp_for_new_connector_integration_frm!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2249,6 +2267,7 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2337,6 +2356,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2425,6 +2445,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2513,6 +2534,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2601,6 +2623,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2686,6 +2709,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2799,6 +2823,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index a53888414a8..3e9d18d117f 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -233,6 +233,7 @@ default_imp_for_complete_authorize!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -327,6 +328,7 @@ default_imp_for_webhook_source_verification!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -421,6 +423,7 @@ default_imp_for_create_customer!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -505,6 +508,7 @@ default_imp_for_connector_redirect_response!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -584,6 +588,7 @@ default_imp_for_connector_request_id!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -682,6 +687,7 @@ default_imp_for_accept_dispute!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -799,6 +805,7 @@ default_imp_for_file_upload!( connector::Tsys, connector::Volt, connector::Opennode, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -894,6 +901,7 @@ default_imp_for_submit_evidence!( connector::Tsys, connector::Volt, connector::Opennode, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -990,6 +998,7 @@ default_imp_for_defend_dispute!( connector::Tsys, connector::Volt, connector::Opennode, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1091,6 +1100,7 @@ default_imp_for_pre_processing_steps!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1171,6 +1181,7 @@ default_imp_for_post_processing_steps!( connector::Threedsecureio, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1246,6 +1257,7 @@ default_imp_for_payouts!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Worldline, connector::Worldpay, connector::Zen, @@ -1339,6 +1351,7 @@ default_imp_for_payouts_create!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Worldline, connector::Worldpay, connector::Zen, @@ -1435,6 +1448,7 @@ default_imp_for_payouts_retrieve!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -1534,6 +1548,7 @@ default_imp_for_payouts_eligibility!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Worldline, connector::Worldpay, connector::Zen, @@ -1624,6 +1639,7 @@ default_imp_for_payouts_fulfill!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Worldline, connector::Worldpay, connector::Zen, @@ -1718,6 +1734,7 @@ default_imp_for_payouts_cancel!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Worldline, connector::Worldpay, connector::Zen, @@ -1814,6 +1831,7 @@ default_imp_for_payouts_quote!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Worldline, connector::Worldpay, connector::Zen, @@ -1909,6 +1927,7 @@ default_imp_for_payouts_recipient!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Worldline, connector::Worldpay, connector::Zen, @@ -2008,6 +2027,7 @@ default_imp_for_payouts_recipient_account!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2105,6 +2125,7 @@ default_imp_for_approve!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2202,6 +2223,7 @@ default_imp_for_reject!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2281,6 +2303,7 @@ default_imp_for_fraud_check!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2378,6 +2401,7 @@ default_imp_for_frm_sale!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2475,6 +2499,7 @@ default_imp_for_frm_checkout!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2572,6 +2597,7 @@ default_imp_for_frm_transaction!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2669,6 +2695,7 @@ default_imp_for_frm_fulfillment!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2766,6 +2793,7 @@ default_imp_for_frm_record_return!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2862,6 +2890,7 @@ default_imp_for_incremental_authorization!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -2955,6 +2984,7 @@ default_imp_for_revoking_mandates!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -3108,6 +3138,7 @@ default_imp_for_connector_authentication!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, @@ -3200,6 +3231,7 @@ default_imp_for_authorize_session_token!( connector::Trustpay, connector::Tsys, connector::Volt, + connector::Wellsfargo, connector::Wise, connector::Worldline, connector::Worldpay, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 727fe158fd4..b2858b23d5b 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -501,6 +501,9 @@ impl ConnectorData { } enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(&connector::Tsys))), enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))), + // enums::Connector::Wellsfargo => { + // Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new()))) + // } enums::Connector::Zen => Ok(ConnectorEnum::Old(Box::new(&connector::Zen))), enums::Connector::Zsl => Ok(ConnectorEnum::Old(Box::new(&connector::Zsl))), enums::Connector::Plaid => { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 64ad3aff030..4805356d3e0 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -297,6 +297,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Trustpay => Self::Trustpay, api_enums::Connector::Tsys => Self::Tsys, api_enums::Connector::Volt => Self::Volt, + // api_enums::Connector::Wellsfargo => Self::Wellsfargo, api_enums::Connector::Wise => Self::Wise, api_enums::Connector::Worldline => Self::Worldline, api_enums::Connector::Worldpay => Self::Worldpay, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 2b8d011cb79..bbf2077f0c9 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -71,6 +71,7 @@ mod trustpay; mod tsys; mod utils; mod volt; +mod wellsfargo; #[cfg(feature = "payouts")] mod wise; mod worldline; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index a39b799b820..0df5cc09b07 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -248,4 +248,9 @@ api_secret = "Razorpay Id" key2 = "Razorpay Secret" [itaubank] -api_key="API Key" \ No newline at end of file +api_key="API Key" + +[wellsfargo] +api_key = "MyApiKey" +key1 = "Merchant id" +api_secret = "Secret key" \ No newline at end of file diff --git a/crates/router/tests/connectors/wellsfargo.rs b/crates/router/tests/connectors/wellsfargo.rs new file mode 100644 index 00000000000..300a5fbb379 --- /dev/null +++ b/crates/router/tests/connectors/wellsfargo.rs @@ -0,0 +1,420 @@ +use masking::Secret; +use router::types::{self, api, domain, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct WellsfargoTest; +impl ConnectorActions for WellsfargoTest {} +impl utils::Connector for WellsfargoTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Wellsfargo; + utils::construct_connector_data_old( + Box::new(Wellsfargo::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .wellsfargo + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "wellsfargo".to_string() + } +} + +static CONNECTOR: WellsfargoTest = WellsfargoTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index b190c009818..13d7da931f6 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -75,6 +75,7 @@ pub struct ConnectorAuthentication { pub trustpay: Option<SignatureKey>, pub tsys: Option<SignatureKey>, pub volt: Option<HeaderKey>, + pub wellsfargo: Option<HeaderKey>, pub wise: Option<BodyKey>, pub worldpay: Option<BodyKey>, pub worldline: Option<SignatureKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index a1fe73bc434..f080fd550d8 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -145,6 +145,7 @@ trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" volt.base_url = "https://api.sandbox.volt.io/" +wellsfargo.base_url = "https://apitest.cybersource.com/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" @@ -216,6 +217,7 @@ cards = [ "trustpay", "tsys", "volt", + "wellsfargo", "wise", "worldline", "worldpay", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 45903461925..62a6140fcc2 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay zsl "$1") + connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe threedsecureio trustpay tsys volt wellsfargo wise worldline worldpay zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2024-07-16T08:00:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added Template code for WellsFargo. Ran add_connector.sh script ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e4b3982c13cedf0f7feaec22df414761e22d98df
juspay/hyperswitch
juspay__hyperswitch-5289
Bug: [FEATURE] [HELCIM] Move connector code for helcim to crate hyperswitch_connectors ### Feature Description Connector code for helcim needs to be moved from crate `router` to new crate `hyperswitch_connectors` ### Possible Implementation Connector code for helcim needs to be moved from crate `router` to new crate `hyperswitch_connectors` ### 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 66b38d09c1f..c5eac1ef868 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3830,6 +3830,25 @@ dependencies = [ "tokio 1.37.0", ] +[[package]] +name = "hyperswitch_connectors" +version = "0.1.0" +dependencies = [ + "api_models", + "async-trait", + "cards", + "common_enums", + "common_utils", + "error-stack", + "hyperswitch_domain_models", + "hyperswitch_interfaces", + "masking", + "router_env", + "serde", + "serde_json", + "strum 0.26.2", +] + [[package]] name = "hyperswitch_constraint_graph" version = "0.1.0" @@ -3892,6 +3911,7 @@ dependencies = [ "router_env", "serde", "serde_json", + "strum 0.26.2", "thiserror", "time", ] @@ -6067,6 +6087,7 @@ dependencies = [ "hex", "http 0.2.12", "hyper 0.14.28", + "hyperswitch_connectors", "hyperswitch_constraint_graph", "hyperswitch_domain_models", "hyperswitch_interfaces", @@ -8371,9 +8392,9 @@ checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517" [[package]] name = "utf8parse" -version = "0.2.2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "utoipa" diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml index a43071b5a17..91bc16f2779 100644 --- a/crates/analytics/Cargo.toml +++ b/crates/analytics/Cargo.toml @@ -18,7 +18,7 @@ common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils" } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } -hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false } masking = { version = "0.1.0", path = "../masking" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 85df79701a7..5d91a477cde 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -35,6 +35,6 @@ vaultrs = { version = "0.7.2", optional = true } # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } -hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false } masking = { version = "0.1.0", path = "../masking" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml new file mode 100644 index 00000000000..0e620c6b9f0 --- /dev/null +++ b/crates/hyperswitch_connectors/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "hyperswitch_connectors" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true + +[features] +frm = ["hyperswitch_domain_models/frm", "hyperswitch_interfaces/frm"] +payouts = ["hyperswitch_domain_models/payouts", "api_models/payouts", "hyperswitch_interfaces/payouts"] + +[dependencies] +async-trait = "0.1.79" +error-stack = "0.4.1" +serde = { version = "1.0.197", features = ["derive"] } +serde_json = "1.0.115" +strum = { version = "0.26", features = ["derive"] } + +# First party crates +api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] , default-features = false} +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", "metrics"] } +hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" , default-features = false } +masking = { version = "0.1.0", path = "../masking" } +router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs new file mode 100644 index 00000000000..a2d78ede2b9 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -0,0 +1,2 @@ +pub mod helcim; +pub use self::helcim::Helcim; diff --git a/crates/router/src/connector/helcim.rs b/crates/hyperswitch_connectors/src/connectors/helcim.rs similarity index 70% rename from crates/router/src/connector/helcim.rs rename to crates/hyperswitch_connectors/src/connectors/helcim.rs index a6305ef6366..8d632d8b7e8 100644 --- a/crates/router/src/connector/helcim.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim.rs @@ -2,30 +2,48 @@ pub mod transformers; use std::fmt::Debug; -use common_utils::request::RequestContent; -use diesel_models::enums; +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::enums; +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; use error_stack::{report, ResultExt}; -use masking::ExposeInterface; -use transformers as helcim; - -use super::utils::{to_connector_meta, PaymentsAuthorizeRequestData}; -use crate::{ - configs::settings, - consts::NO_ERROR_CODE, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, }, - utils::{self, BytesExt}, +}; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + consts::NO_ERROR_CODE, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::{ExposeInterface, Mask}; +use transformers as helcim; + +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{to_connector_meta, PaymentsAuthorizeRequestData}, }; #[derive(Debug, Clone)] @@ -54,12 +72,8 @@ impl Helcim { } } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Helcim +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Helcim { // Not Implemented (R) } @@ -70,9 +84,10 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), @@ -83,7 +98,7 @@ where const ID_LENGTH: usize = 22; let mut idempotency_key = vec![( headers::IDEMPOTENCY_KEY.to_string(), - utils::generate_id(ID_LENGTH, "HS").into_masked(), + common_utils::generate_id(ID_LENGTH, "HS").into_masked(), )]; header.append(&mut api_key); @@ -105,14 +120,15 @@ impl ConnectorCommon for Helcim { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.helcim.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { let auth = helcim::HelcimAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( @@ -163,49 +179,39 @@ impl ConnectorValidation for Helcim { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - super::utils::construct_not_supported_error_report(capture_method, self.id()), + crate::utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Helcim -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Helcim { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Helcim -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Helcim {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Helcim -{ +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Helcim { fn get_headers( &self, - req: &types::SetupMandateRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::SetupMandateRouterData, - connectors: &settings::Connectors, + _req: &SetupMandateRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/payment/verify", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::SetupMandateRouterData, - _connectors: &settings::Connectors, + req: &SetupMandateRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = helcim::HelcimVerifyRequest::try_from(req)?; @@ -213,17 +219,17 @@ impl } fn build_request( &self, - _req: &types::SetupMandateRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &SetupMandateRouterData, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Helcim".to_string()) .into(), ) // Ok(Some( - // services::RequestBuilder::new() - // .method(services::Method::Post) + // RequestBuilder::new() + // .method(Method::Post) // .url(&types::SetupMandateType::get_url(self, req, connectors)?) // .attach_default_headers() // .headers(types::SetupMandateType::get_headers(self, req, connectors)?) @@ -235,17 +241,17 @@ impl } fn handle_response( &self, - data: &types::SetupMandateRouterData, + data: &SetupMandateRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { + ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("Helcim PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -260,14 +266,13 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Helcim -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Helcim { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { self.build_headers(req, connectors) } @@ -277,8 +282,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { if req.request.is_auto_capture()? { return Ok(format!("{}v2/payment/purchase", self.base_url(connectors))); @@ -288,8 +293,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = helcim::HelcimRouterData::try_from(( &self.get_currency_unit(), @@ -303,12 +308,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) @@ -325,10 +330,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("Helcim PaymentsAuthorizeResponse") @@ -337,7 +342,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -353,14 +358,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Helcim -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Helcim { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::PaymentsSyncType::get_content_type(self) @@ -378,8 +382,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req .request @@ -395,12 +399,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) @@ -410,10 +414,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("helcim PaymentsSyncResponse") @@ -422,7 +426,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -444,14 +448,13 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe // } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Helcim -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Helcim { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { self.build_headers(req, connectors) } @@ -461,16 +464,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, - _req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, + _req: &PaymentsCaptureRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/payment/capture", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = helcim::HelcimRouterData::try_from(( &self.get_currency_unit(), @@ -484,12 +487,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( @@ -504,10 +507,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("Helcim PaymentsCaptureResponse") @@ -516,7 +519,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -532,14 +535,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Helcim -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Helcim { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { self.build_headers(req, connectors) } @@ -549,16 +551,16 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_url( &self, - _req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, + _req: &PaymentsCancelRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/payment/reverse", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, + req: &PaymentsCancelRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = helcim::HelcimVoidRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -566,12 +568,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) @@ -584,10 +586,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("HelcimPaymentsResponse") @@ -596,7 +598,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -613,12 +615,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } } -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Helcim { +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Helcim { fn get_headers( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { self.build_headers(req, connectors) } @@ -628,16 +631,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, + _req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/payment/refund", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = helcim::HelcimRouterData::try_from(( &self.get_currency_unit(), @@ -651,11 +654,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn build_request( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( @@ -670,10 +673,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: helcim::RefundResponse = res.response .parse_struct("helcim RefundResponse") @@ -682,7 +685,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -698,12 +701,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Helcim { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Helcim { fn get_headers( &self, - req: &types::RefundSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::maskable::Maskable<String>)>, errors::ConnectorError> + { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::RefundSyncType::get_content_type(self) @@ -721,8 +725,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_refund_id = req .request @@ -738,12 +742,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn build_request( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) @@ -753,10 +757,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, - data: &types::RefundSyncRouterData, + data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: helcim::RefundResponse = res .response .parse_struct("helcim RefundSyncResponse") @@ -765,7 +769,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -782,24 +786,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse } #[async_trait::async_trait] -impl api::IncomingWebhook for Helcim { +impl IncomingWebhook for Helcim { fn get_webhook_object_reference_id( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs similarity index 70% rename from crates/router/src/connector/helcim/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs index 2f6cf61e759..3aed97a2cbc 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs @@ -1,16 +1,34 @@ +use common_enums::enums; use common_utils::pii::{Email, IpAddress}; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + payment_method_data::{Card, PaymentMethodData}, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::{ + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, + ResponseId, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + RefundsRouterData, SetupMandateRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{self}, + errors, +}; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{ - self, AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{ + AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, PaymentsCaptureRequestData, PaymentsSetupMandateRequestData, - RefundsRequestData, RouterData, + RefundsRequestData, RouterData as RouterDataUtils, }, - core::errors, - types::{self, api, domain, storage::enums}, }; #[derive(Debug, Serialize)] @@ -24,7 +42,7 @@ impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for HelcimRouterD fn try_from( (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { - let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; + let amount = crate::utils::get_amount_as_f64(currency_unit, amount, currency)?; Ok(Self { amount, router_data: item, @@ -109,11 +127,9 @@ pub struct HelcimCard { card_c_v_v: Secret<String>, } -impl TryFrom<(&types::SetupMandateRouterData, &domain::Card)> for HelcimVerifyRequest { +impl TryFrom<(&SetupMandateRouterData, &Card)> for HelcimVerifyRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - value: (&types::SetupMandateRouterData, &domain::Card), - ) -> Result<Self, Self::Error> { + fn try_from(value: (&SetupMandateRouterData, &Card)) -> Result<Self, Self::Error> { let (item, req_card) = value; let card_data = HelcimCard { card_expiry: req_card @@ -143,48 +159,38 @@ impl TryFrom<(&types::SetupMandateRouterData, &domain::Card)> for HelcimVerifyRe } } -impl TryFrom<&types::SetupMandateRouterData> for HelcimVerifyRequest { +impl TryFrom<&SetupMandateRouterData> for HelcimVerifyRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { - domain::PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)), - domain::PaymentMethodData::BankTransfer(_) => { + PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)), + PaymentMethodData::BankTransfer(_) => { Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()) } - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Helcim"), - ))? - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + crate::utils::get_unimplemented_payment_method_error_message("Helcim"), + ))?, } } } -impl - TryFrom<( - &HelcimRouterData<&types::PaymentsAuthorizeRouterData>, - &domain::Card, - )> for HelcimPaymentsRequest -{ +impl TryFrom<(&HelcimRouterData<&PaymentsAuthorizeRouterData>, &Card)> for HelcimPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - value: ( - &HelcimRouterData<&types::PaymentsAuthorizeRouterData>, - &domain::Card, - ), + value: (&HelcimRouterData<&PaymentsAuthorizeRouterData>, &Card), ) -> Result<Self, Self::Error> { let (item, req_card) = value; let card_data = HelcimCard { @@ -198,7 +204,7 @@ impl .get_billing()? .to_owned() .address - .ok_or_else(utils::missing_field_err("billing.address"))?; + .ok_or_else(crate::utils::missing_field_err("billing.address"))?; let billing_address = HelcimBillingAddress { name: req_address.get_full_name()?, @@ -244,34 +250,32 @@ impl } } -impl TryFrom<&HelcimRouterData<&types::PaymentsAuthorizeRouterData>> for HelcimPaymentsRequest { +impl TryFrom<&HelcimRouterData<&PaymentsAuthorizeRouterData>> for HelcimPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: &HelcimRouterData<&types::PaymentsAuthorizeRouterData>, + item: &HelcimRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - domain::PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)), - domain::PaymentMethodData::BankTransfer(_) => { + PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)), + PaymentMethodData::BankTransfer(_) => { Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()) } - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Helcim"), - ))? - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + crate::utils::get_unimplemented_payment_method_error_message("Helcim"), + ))?, } } } @@ -281,11 +285,11 @@ pub struct HelcimAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for HelcimAuthType { +impl TryFrom<&ConnectorAuthType> for HelcimAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), @@ -345,26 +349,26 @@ pub struct HelcimPaymentsResponse { impl<F> TryFrom< - types::ResponseRouterData< + ResponseRouterData< F, HelcimPaymentsResponse, - types::SetupMandateRequestData, - types::PaymentsResponseData, + SetupMandateRequestData, + PaymentsResponseData, >, - > for types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData> + > for RouterData<F, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< + item: ResponseRouterData< F, HelcimPaymentsResponse, - types::SetupMandateRequestData, - types::PaymentsResponseData, + SetupMandateRequestData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_string(), ), redirection_data: None, @@ -388,30 +392,25 @@ pub struct HelcimMetaData { impl<F> TryFrom< - types::ResponseRouterData< - F, - HelcimPaymentsResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - >, - > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> + ResponseRouterData<F, HelcimPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>, + > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< + item: ResponseRouterData< F, HelcimPaymentsResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { //PreAuth Transaction ID is stored in connector metadata //Initially resource_id is stored as NoResponseID for manual capture //After Capture Transaction is completed it is updated to store the Capture ID let resource_id = if item.data.request.is_auto_capture()? { - types::ResponseId::ConnectorTransactionId(item.response.transaction_id.to_string()) + ResponseId::ConnectorTransactionId(item.response.transaction_id.to_string()) } else { - types::ResponseId::NoResponseId + ResponseId::NoResponseId }; let connector_metadata = if !item.data.request.is_auto_capture()? { Some(serde_json::json!(HelcimMetaData { @@ -421,7 +420,7 @@ impl<F> None }; Ok(Self { - response: Ok(types::PaymentsResponseData::TransactionResponse { + response: Ok(PaymentsResponseData::TransactionResponse { resource_id, redirection_data: None, mandate_reference: None, @@ -459,28 +458,17 @@ impl<F> // } impl<F> - TryFrom< - types::ResponseRouterData< - F, - HelcimPaymentsResponse, - types::PaymentsSyncData, - types::PaymentsResponseData, - >, - > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData> + TryFrom<ResponseRouterData<F, HelcimPaymentsResponse, PaymentsSyncData, PaymentsResponseData>> + for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - HelcimPaymentsResponse, - types::PaymentsSyncData, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, HelcimPaymentsResponse, PaymentsSyncData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.data.request.sync_type { - types::SyncRequestType::SinglePaymentSync => Ok(Self { - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + hyperswitch_domain_models::router_request_types::SyncRequestType::SinglePaymentSync => Ok(Self { + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_string(), ), redirection_data: None, @@ -494,7 +482,7 @@ impl<F> status: enums::AttemptStatus::from(item.response), ..item.data }), - types::SyncRequestType::MultipleCaptureSync(_) => { + hyperswitch_domain_models::router_request_types::SyncRequestType::MultipleCaptureSync(_) => { Err(errors::ConnectorError::NotImplemented( "manual multiple capture sync".to_string(), ) @@ -502,7 +490,7 @@ impl<F> // let capture_sync_response_list = // utils::construct_captures_response_hashmap(vec![item.response]); // Ok(Self { - // response: Ok(types::PaymentsResponseData::MultipleCaptureResponse { + // response: Ok(PaymentsResponseData::MultipleCaptureResponse { // capture_sync_response_list, // }), // ..item.data @@ -522,11 +510,9 @@ pub struct HelcimCaptureRequest { ecommerce: Option<bool>, } -impl TryFrom<&HelcimRouterData<&types::PaymentsCaptureRouterData>> for HelcimCaptureRequest { +impl TryFrom<&HelcimRouterData<&PaymentsCaptureRouterData>> for HelcimCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &HelcimRouterData<&types::PaymentsCaptureRouterData>, - ) -> Result<Self, Self::Error> { + fn try_from(item: &HelcimRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let ip_address = item .router_data .request @@ -548,26 +534,21 @@ impl TryFrom<&HelcimRouterData<&types::PaymentsCaptureRouterData>> for HelcimCap impl<F> TryFrom< - types::ResponseRouterData< - F, - HelcimPaymentsResponse, - types::PaymentsCaptureData, - types::PaymentsResponseData, - >, - > for types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData> + ResponseRouterData<F, HelcimPaymentsResponse, PaymentsCaptureData, PaymentsResponseData>, + > for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< + item: ResponseRouterData< F, HelcimPaymentsResponse, - types::PaymentsCaptureData, - types::PaymentsResponseData, + PaymentsCaptureData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_string(), ), redirection_data: None, @@ -593,9 +574,9 @@ pub struct HelcimVoidRequest { ecommerce: Option<bool>, } -impl TryFrom<&types::PaymentsCancelRouterData> for HelcimVoidRequest { +impl TryFrom<&PaymentsCancelRouterData> for HelcimVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let ip_address = item.request.get_browser_info()?.get_ip_address()?; Ok(Self { card_transaction_id: item @@ -610,27 +591,21 @@ impl TryFrom<&types::PaymentsCancelRouterData> for HelcimVoidRequest { } impl<F> - TryFrom< - types::ResponseRouterData< - F, - HelcimPaymentsResponse, - types::PaymentsCancelData, - types::PaymentsResponseData, - >, - > for types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData> + TryFrom<ResponseRouterData<F, HelcimPaymentsResponse, PaymentsCancelData, PaymentsResponseData>> + for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< + item: ResponseRouterData< F, HelcimPaymentsResponse, - types::PaymentsCancelData, - types::PaymentsResponseData, + PaymentsCancelData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_string(), ), redirection_data: None, @@ -659,11 +634,9 @@ pub struct HelcimRefundRequest { ecommerce: Option<bool>, } -impl<F> TryFrom<&HelcimRouterData<&types::RefundsRouterData<F>>> for HelcimRefundRequest { +impl<F> TryFrom<&HelcimRouterData<&RefundsRouterData<F>>> for HelcimRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &HelcimRouterData<&types::RefundsRouterData<F>>, - ) -> Result<Self, Self::Error> { + fn try_from(item: &HelcimRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let original_transaction_id = item .router_data .request @@ -710,15 +683,13 @@ impl From<RefundResponse> for enums::RefundStatus { } } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> -{ +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_id.to_string(), refund_status: enums::RefundStatus::from(item.response), }), @@ -727,15 +698,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_id.to_string(), refund_status: enums::RefundStatus::from(item.response), }), diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs new file mode 100644 index 00000000000..9f5285bd2e1 --- /dev/null +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -0,0 +1,6 @@ +/// Header Constants +pub(crate) mod headers { + pub(crate) const API_TOKEN: &str = "Api-Token"; + pub(crate) const CONTENT_TYPE: &str = "Content-Type"; + pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key"; +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs new file mode 100644 index 00000000000..2273b8c31da --- /dev/null +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -0,0 +1,562 @@ +// impl api::PaymentIncrementalAuthorization for Helcim {} +// impl api::ConnectorCustomer for Helcim {} +// impl api::PaymentsPreProcessing for Helcim {} +// impl api::PaymentReject for Helcim {} +// impl api::PaymentApprove for Helcim {} +#[cfg(feature = "frm")] +use hyperswitch_domain_models::{ + router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, + PoSync, + }, + router_request_types::PayoutsData, + router_response_types::PayoutsResponseData, +}; +use hyperswitch_domain_models::{ + router_flow_types::{ + dispute::{Accept, Defend, Evidence}, + files::{Retrieve, Upload}, + mandate_revoke::MandateRevoke, + payments::{ + Approve, AuthorizeSessionToken, CompleteAuthorize, CreateConnectorCustomer, + IncrementalAuthorization, PostProcessing, PreProcessing, Reject, + }, + webhooks::VerifyWebhookSource, + }, + router_request_types::{ + AcceptDisputeRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, + ConnectorCustomerData, DefendDisputeRequestData, MandateRevokeRequestData, + PaymentsApproveData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsPreProcessingData, PaymentsRejectData, RetrieveFileRequestData, + SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData, + }, + router_response_types::{ + AcceptDisputeResponse, DefendDisputeResponse, MandateRevokeResponseData, + PaymentsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, UploadFileResponse, + VerifyWebhookSourceResponseData, + }, +}; +#[cfg(feature = "frm")] +use hyperswitch_interfaces::api::fraud_check::{ + FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, + FraudCheckTransaction, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::api::payouts::{ + PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient, + PayoutRecipientAccount, PayoutSync, +}; +use hyperswitch_interfaces::api::{ + self, + disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence}, + files::{FileUpload, RetrieveFile, UploadFile}, + payments::{ + ConnectorCustomer, PaymentApprove, PaymentAuthorizeSessionToken, + PaymentIncrementalAuthorization, PaymentReject, PaymentsCompleteAuthorize, + PaymentsPostProcessing, PaymentsPreProcessing, + }, + ConnectorIntegration, ConnectorMandateRevoke, +}; + +macro_rules! default_imp_for_authorize_session_token { + ($($path:ident::$connector:ident),*) => { + $( impl PaymentAuthorizeSessionToken for $path::$connector {} + impl + ConnectorIntegration< + AuthorizeSessionToken, + AuthorizeSessionTokenData, + PaymentsResponseData + > for $path::$connector + {} + )* + }; +} + +default_imp_for_authorize_session_token!(connectors::Helcim); + +use crate::connectors; +macro_rules! default_imp_for_complete_authorize { + ($($path:ident::$connector:ident),*) => { + $( + impl PaymentsCompleteAuthorize for $path::$connector {} + impl + ConnectorIntegration< + CompleteAuthorize, + CompleteAuthorizeData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_complete_authorize!(connectors::Helcim); + +macro_rules! default_imp_for_incremental_authorization { + ($($path:ident::$connector:ident),*) => { + $( + impl PaymentIncrementalAuthorization for $path::$connector {} + impl + ConnectorIntegration< + IncrementalAuthorization, + PaymentsIncrementalAuthorizationData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_incremental_authorization!(connectors::Helcim); + +macro_rules! default_imp_for_create_customer { + ($($path:ident::$connector:ident),*) => { + $( + impl ConnectorCustomer for $path::$connector {} + impl + ConnectorIntegration< + CreateConnectorCustomer, + ConnectorCustomerData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_create_customer!(connectors::Helcim); + +macro_rules! default_imp_for_pre_processing_steps{ + ($($path:ident::$connector:ident),*)=> { + $( + impl PaymentsPreProcessing for $path::$connector {} + impl + ConnectorIntegration< + PreProcessing, + PaymentsPreProcessingData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_pre_processing_steps!(connectors::Helcim); + +macro_rules! default_imp_for_post_processing_steps{ + ($($path:ident::$connector:ident),*)=> { + $( + impl PaymentsPostProcessing for $path::$connector {} + impl + ConnectorIntegration< + PostProcessing, + PaymentsPostProcessingData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_post_processing_steps!(connectors::Helcim); + +macro_rules! default_imp_for_approve { + ($($path:ident::$connector:ident),*) => { + $( + impl PaymentApprove for $path::$connector {} + impl + ConnectorIntegration< + Approve, + PaymentsApproveData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_approve!(connectors::Helcim); + +macro_rules! default_imp_for_reject { + ($($path:ident::$connector:ident),*) => { + $( + impl PaymentReject for $path::$connector {} + impl + ConnectorIntegration< + Reject, + PaymentsRejectData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_reject!(connectors::Helcim); + +macro_rules! default_imp_for_webhook_source_verification { + ($($path:ident::$connector:ident),*) => { + $( + impl api::ConnectorVerifyWebhookSource for $path::$connector {} + impl + ConnectorIntegration< + VerifyWebhookSource, + VerifyWebhookSourceRequestData, + VerifyWebhookSourceResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_webhook_source_verification!(connectors::Helcim); + +macro_rules! default_imp_for_accept_dispute { + ($($path:ident::$connector:ident),*) => { + $( + impl Dispute for $path::$connector {} + impl AcceptDispute for $path::$connector {} + impl + ConnectorIntegration< + Accept, + AcceptDisputeRequestData, + AcceptDisputeResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_accept_dispute!(connectors::Helcim); + +macro_rules! default_imp_for_submit_evidence { + ($($path:ident::$connector:ident),*) => { + $( + impl SubmitEvidence for $path::$connector {} + impl + ConnectorIntegration< + Evidence, + SubmitEvidenceRequestData, + SubmitEvidenceResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_submit_evidence!(connectors::Helcim); + +macro_rules! default_imp_for_defend_dispute { + ($($path:ident::$connector:ident),*) => { + $( + impl DefendDispute for $path::$connector {} + impl + ConnectorIntegration< + Defend, + DefendDisputeRequestData, + DefendDisputeResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_defend_dispute!(connectors::Helcim); + +macro_rules! default_imp_for_file_upload { + ($($path:ident::$connector:ident),*) => { + $( + impl FileUpload for $path::$connector {} + impl UploadFile for $path::$connector {} + impl + ConnectorIntegration< + Upload, + UploadFileRequestData, + UploadFileResponse, + > for $path::$connector + {} + impl RetrieveFile for $path::$connector {} + impl + ConnectorIntegration< + Retrieve, + RetrieveFileRequestData, + RetrieveFileResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_file_upload!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_create { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutCreate for $path::$connector {} + impl + ConnectorIntegration< + PoCreate, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_create!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_retrieve { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutSync for $path::$connector {} + impl + ConnectorIntegration< + PoSync, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_retrieve!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_eligibility { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutEligibility for $path::$connector {} + impl + ConnectorIntegration< + PoEligibility, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_eligibility!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_fulfill { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutFulfill for $path::$connector {} + impl + ConnectorIntegration< + PoFulfill, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_fulfill!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_cancel { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutCancel for $path::$connector {} + impl + ConnectorIntegration< + PoCancel, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_cancel!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_quote { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutQuote for $path::$connector {} + impl + ConnectorIntegration< + PoQuote, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_quote!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_recipient { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutRecipient for $path::$connector {} + impl + ConnectorIntegration< + PoRecipient, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_recipient!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_recipient_account { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutRecipientAccount for $path::$connector {} + impl + ConnectorIntegration< + PoRecipientAccount, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_recipient_account!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_frm_sale { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckSale for $path::$connector {} + impl + ConnectorIntegration< + Sale, + FraudCheckSaleData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_frm_sale!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_frm_checkout { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckCheckout for $path::$connector {} + impl + ConnectorIntegration< + Checkout, + FraudCheckCheckoutData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_frm_checkout!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_frm_transaction { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckTransaction for $path::$connector {} + impl + ConnectorIntegration< + Transaction, + FraudCheckTransactionData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_frm_transaction!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_frm_fulfillment { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckFulfillment for $path::$connector {} + impl + ConnectorIntegration< + Fulfillment, + FraudCheckFulfillmentData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_frm_fulfillment!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_frm_record_return { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckRecordReturn for $path::$connector {} + impl + ConnectorIntegration< + RecordReturn, + FraudCheckRecordReturnData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_frm_record_return!(connectors::Helcim); + +macro_rules! default_imp_for_revoking_mandates { + ($($path:ident::$connector:ident),*) => { + $( impl ConnectorMandateRevoke for $path::$connector {} + impl + ConnectorIntegration< + MandateRevoke, + MandateRevokeRequestData, + MandateRevokeResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_revoking_mandates!(connectors::Helcim); diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs new file mode 100644 index 00000000000..df72d3d9c48 --- /dev/null +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -0,0 +1,592 @@ +use hyperswitch_domain_models::{ + router_data::AccessToken, + router_data_v2::{ + flow_common_types::{ + DisputesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, + WebhookSourceVerifyData, + }, + AccessTokenFlowData, FilesFlowData, + }, + router_flow_types::{ + dispute::{Accept, Defend, Evidence}, + files::{Retrieve, Upload}, + mandate_revoke::MandateRevoke, + payments::{ + Approve, Authorize, AuthorizeSessionToken, Capture, CompleteAuthorize, + CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, + PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, + }, + refunds::{Execute, RSync}, + webhooks::VerifyWebhookSource, + AccessTokenAuth, + }, + router_request_types::{ + AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, + CompleteAuthorizeData, ConnectorCustomerData, DefendDisputeRequestData, + MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsApproveData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, + PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, + RefundsData, RetrieveFileRequestData, SetupMandateRequestData, SubmitEvidenceRequestData, + UploadFileRequestData, VerifyWebhookSourceRequestData, + }, + router_response_types::{ + AcceptDisputeResponse, DefendDisputeResponse, MandateRevokeResponseData, + PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, + UploadFileResponse, VerifyWebhookSourceResponseData, + }, +}; +#[cfg(feature = "frm")] +use hyperswitch_domain_models::{ + router_data_v2::FrmFlowData, + router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_data_v2::PayoutFlowData, + router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, + PoSync, + }, + router_request_types::PayoutsData, + router_response_types::PayoutsResponseData, +}; +#[cfg(feature = "frm")] +use hyperswitch_interfaces::api::fraud_check_v2::{ + FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2, + FraudCheckTransactionV2, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::api::payouts_v2::{ + PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2, + PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2, +}; +use hyperswitch_interfaces::{ + api::{ + disputes_v2::{AcceptDisputeV2, DefendDisputeV2, DisputeV2, SubmitEvidenceV2}, + files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2}, + payments_v2::{ + ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, + PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, + PaymentRejectV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, + PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, + PaymentsPreProcessingV2, + }, + refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2}, + ConnectorAccessTokenV2, ConnectorMandateRevokeV2, ConnectorVerifyWebhookSourceV2, + }, + connector_integration_v2::ConnectorIntegrationV2, +}; + +use crate::connectors; + +macro_rules! default_imp_for_new_connector_integration_payment { + ($($path:ident::$connector:ident),*) => { + $( + impl PaymentV2 for $path::$connector{} + impl PaymentAuthorizeV2 for $path::$connector{} + impl PaymentAuthorizeSessionTokenV2 for $path::$connector{} + impl PaymentSyncV2 for $path::$connector{} + impl PaymentVoidV2 for $path::$connector{} + impl PaymentApproveV2 for $path::$connector{} + impl PaymentRejectV2 for $path::$connector{} + impl PaymentCaptureV2 for $path::$connector{} + impl PaymentSessionV2 for $path::$connector{} + impl MandateSetupV2 for $path::$connector{} + impl PaymentIncrementalAuthorizationV2 for $path::$connector{} + impl PaymentsCompleteAuthorizeV2 for $path::$connector{} + impl PaymentTokenV2 for $path::$connector{} + impl ConnectorCustomerV2 for $path::$connector{} + impl PaymentsPreProcessingV2 for $path::$connector{} + impl PaymentsPostProcessingV2 for $path::$connector{} + impl + ConnectorIntegrationV2<Authorize,PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2<PSync,PaymentFlowData, PaymentsSyncData, PaymentsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2<Approve,PaymentFlowData, PaymentsApproveData, PaymentsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2<Reject,PaymentFlowData, PaymentsRejectData, PaymentsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2<Capture,PaymentFlowData, PaymentsCaptureData, PaymentsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2<Session,PaymentFlowData, PaymentsSessionData, PaymentsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2<SetupMandate,PaymentFlowData, SetupMandateRequestData, PaymentsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2< + IncrementalAuthorization, + PaymentFlowData, + PaymentsIncrementalAuthorizationData, + PaymentsResponseData, + > + for $path::$connector{} + impl + ConnectorIntegrationV2< + CompleteAuthorize, + PaymentFlowData, + CompleteAuthorizeData, + PaymentsResponseData, + > for $path::$connector{} + impl + ConnectorIntegrationV2< + PaymentMethodToken, + PaymentFlowData, + PaymentMethodTokenizationData, + PaymentsResponseData, + > for $path::$connector{} + impl + ConnectorIntegrationV2< + CreateConnectorCustomer, + PaymentFlowData, + ConnectorCustomerData, + PaymentsResponseData, + > for $path::$connector{} + impl ConnectorIntegrationV2< + PreProcessing, + PaymentFlowData, + PaymentsPreProcessingData, + PaymentsResponseData, + > for $path::$connector{} + impl ConnectorIntegrationV2< + PostProcessing, + PaymentFlowData, + PaymentsPostProcessingData, + PaymentsResponseData, + > for $path::$connector{} + impl + ConnectorIntegrationV2< + AuthorizeSessionToken, + PaymentFlowData, + AuthorizeSessionTokenData, + PaymentsResponseData + > for $path::$connector{} + )* + }; +} + +default_imp_for_new_connector_integration_payment!(connectors::Helcim); + +macro_rules! default_imp_for_new_connector_integration_refund { + ($($path:ident::$connector:ident),*) => { + $( + impl RefundV2 for $path::$connector{} + impl RefundExecuteV2 for $path::$connector{} + impl RefundSyncV2 for $path::$connector{} + impl + ConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData> + for $path::$connector{} + impl + ConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData> + for $path::$connector{} + )* + }; +} + +default_imp_for_new_connector_integration_refund!(connectors::Helcim); + +macro_rules! default_imp_for_new_connector_integration_connector_access_token { + ($($path:ident::$connector:ident),*) => { + $( + impl ConnectorAccessTokenV2 for $path::$connector{} + impl + ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken> + for $path::$connector{} + )* + }; +} + +default_imp_for_new_connector_integration_connector_access_token!(connectors::Helcim); + +macro_rules! default_imp_for_new_connector_integration_accept_dispute { + ($($path:ident::$connector:ident),*) => { + $( + impl DisputeV2 for $path::$connector {} + impl AcceptDisputeV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Accept, + DisputesFlowData, + AcceptDisputeRequestData, + AcceptDisputeResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_new_connector_integration_accept_dispute!(connectors::Helcim); + +macro_rules! default_imp_for_new_connector_integration_submit_evidence { + ($($path:ident::$connector:ident),*) => { + $( + impl SubmitEvidenceV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Evidence, + DisputesFlowData, + SubmitEvidenceRequestData, + SubmitEvidenceResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_new_connector_integration_submit_evidence!(connectors::Helcim); + +macro_rules! default_imp_for_new_connector_integration_defend_dispute { + ($($path:ident::$connector:ident),*) => { + $( + impl DefendDisputeV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Defend, + DisputesFlowData, + DefendDisputeRequestData, + DefendDisputeResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_new_connector_integration_defend_dispute!(connectors::Helcim); + +macro_rules! default_imp_for_new_connector_integration_file_upload { + ($($path:ident::$connector:ident),*) => { + $( + impl FileUploadV2 for $path::$connector {} + impl UploadFileV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Upload, + FilesFlowData, + UploadFileRequestData, + UploadFileResponse, + > for $path::$connector + {} + impl RetrieveFileV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Retrieve, + FilesFlowData, + RetrieveFileRequestData, + RetrieveFileResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_new_connector_integration_file_upload!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_new_connector_integration_payouts_create { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutCreateV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + PoCreate, + PayoutFlowData, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_new_connector_integration_payouts_create!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_new_connector_integration_payouts_eligibility { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutEligibilityV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + PoEligibility, + PayoutFlowData, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_new_connector_integration_payouts_eligibility!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_new_connector_integration_payouts_fulfill { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutFulfillV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + PoFulfill, + PayoutFlowData, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_new_connector_integration_payouts_fulfill!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_new_connector_integration_payouts_cancel { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutCancelV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + PoCancel, + PayoutFlowData, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_new_connector_integration_payouts_cancel!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_new_connector_integration_payouts_quote { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutQuoteV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + PoQuote, + PayoutFlowData, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_new_connector_integration_payouts_quote!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_new_connector_integration_payouts_recipient { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutRecipientV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + PoRecipient, + PayoutFlowData, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_new_connector_integration_payouts_recipient!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_new_connector_integration_payouts_sync { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutSyncV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + PoSync, + PayoutFlowData, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_new_connector_integration_payouts_sync!(connectors::Helcim); + +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account { + ($($path:ident::$connector:ident),*) => { + $( + impl PayoutRecipientAccountV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + PoRecipientAccount, + PayoutFlowData, + PayoutsData, + PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +default_imp_for_new_connector_integration_payouts_recipient_account!(connectors::Helcim); + +macro_rules! default_imp_for_new_connector_integration_webhook_source_verification { + ($($path:ident::$connector:ident),*) => { + $( + impl ConnectorVerifyWebhookSourceV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + VerifyWebhookSource, + WebhookSourceVerifyData, + VerifyWebhookSourceRequestData, + VerifyWebhookSourceResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_new_connector_integration_webhook_source_verification!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_new_connector_integration_frm_sale { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckSaleV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Sale, + FrmFlowData, + FraudCheckSaleData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_new_connector_integration_frm_sale!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_new_connector_integration_frm_checkout { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckCheckoutV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Checkout, + FrmFlowData, + FraudCheckCheckoutData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_new_connector_integration_frm_checkout!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_new_connector_integration_frm_transaction { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckTransactionV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Transaction, + FrmFlowData, + FraudCheckTransactionData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_new_connector_integration_frm_transaction!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_new_connector_integration_frm_fulfillment { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckFulfillmentV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + Fulfillment, + FrmFlowData, + FraudCheckFulfillmentData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_new_connector_integration_frm_fulfillment!(connectors::Helcim); + +#[cfg(feature = "frm")] +macro_rules! default_imp_for_new_connector_integration_frm_record_return { + ($($path:ident::$connector:ident),*) => { + $( + impl FraudCheckRecordReturnV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + RecordReturn, + FrmFlowData, + FraudCheckRecordReturnData, + FraudCheckResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "frm")] +default_imp_for_new_connector_integration_frm_record_return!(connectors::Helcim); + +macro_rules! default_imp_for_new_connector_integration_revoking_mandates { + ($($path:ident::$connector:ident),*) => { + $( impl ConnectorMandateRevokeV2 for $path::$connector {} + impl + ConnectorIntegrationV2< + MandateRevoke, + MandateRevokeFlowData, + MandateRevokeRequestData, + MandateRevokeResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_new_connector_integration_revoking_mandates!(connectors::Helcim); diff --git a/crates/hyperswitch_connectors/src/lib.rs b/crates/hyperswitch_connectors/src/lib.rs new file mode 100644 index 00000000000..aa0ff7e975e --- /dev/null +++ b/crates/hyperswitch_connectors/src/lib.rs @@ -0,0 +1,8 @@ +//! Hyperswitch connectors + +pub mod connectors; +pub mod constants; +pub mod default_implementations; +pub mod default_implementations_v2; +pub mod types; +pub mod utils; diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs new file mode 100644 index 00000000000..3238bd5e82f --- /dev/null +++ b/crates/hyperswitch_connectors/src/types.rs @@ -0,0 +1,14 @@ +use hyperswitch_domain_models::{ + router_data::RouterData, router_request_types::RefundsData, + router_response_types::RefundsResponseData, +}; + +pub(crate) type RefundsResponseRouterData<F, R> = + ResponseRouterData<F, R, RefundsData, RefundsResponseData>; + +// TODO: Remove `ResponseRouterData` from router crate after all the related type aliases are moved to this crate. +pub struct ResponseRouterData<Flow, R, Request, Response> { + pub response: R, + pub data: RouterData<Flow, Request, Response>, + pub http_code: u16, +} diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs new file mode 100644 index 00000000000..0b8ecac9b07 --- /dev/null +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -0,0 +1,1077 @@ +use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount, PhoneDetails}; +use common_enums::{enums, enums::FutureUsage}; +use common_utils::{ + errors::ReportSwitchExt, + ext_traits::{OptionExt, ValueExt}, + id_type, + pii::{self, Email, IpAddress}, +}; +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + payment_method_data::{Card, PaymentMethodData}, + router_data::{PaymentMethodToken, RecurringMandatePaymentData}, + router_request_types::{ + AuthenticationData, BrowserInformation, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCaptureData, RefundsData, SetupMandateRequestData, + }, +}; +use hyperswitch_interfaces::{api, errors}; +use masking::{ExposeInterface, PeekInterface, Secret}; + +type Error = error_stack::Report<errors::ConnectorError>; + +pub(crate) fn construct_not_supported_error_report( + capture_method: enums::CaptureMethod, + connector_name: &'static str, +) -> error_stack::Report<errors::ConnectorError> { + errors::ConnectorError::NotSupported { + message: capture_method.to_string(), + connector: connector_name, + } + .into() +} + +pub(crate) fn get_amount_as_f64( + currency_unit: &api::CurrencyUnit, + amount: i64, + currency: enums::Currency, +) -> Result<f64, error_stack::Report<errors::ConnectorError>> { + let amount = match currency_unit { + api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?, + api::CurrencyUnit::Minor => u32::try_from(amount) + .change_context(errors::ConnectorError::ParsingFailed)? + .into(), + }; + Ok(amount) +} + +pub(crate) fn to_currency_base_unit_asf64( + amount: i64, + currency: enums::Currency, +) -> Result<f64, error_stack::Report<errors::ConnectorError>> { + currency + .to_currency_base_unit_asf64(amount) + .change_context(errors::ConnectorError::ParsingFailed) +} + +pub(crate) fn missing_field_err( + message: &'static str, +) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + '_> { + Box::new(move || { + errors::ConnectorError::MissingRequiredField { + field_name: message, + } + .into() + }) +} + +pub(crate) const SELECTED_PAYMENT_METHOD: &str = "Selected payment method"; + +pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String { + format!("{} through {}", SELECTED_PAYMENT_METHOD, connector) +} + +pub(crate) fn to_connector_meta<T>(connector_meta: Option<serde_json::Value>) -> Result<T, Error> +where + T: serde::de::DeserializeOwned, +{ + let json = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?; + json.parse_value(std::any::type_name::<T>()).switch() +} + +// TODO: Make all traits as `pub(crate) trait` once all connectors are moved. +pub trait RouterData { + fn get_billing(&self) -> Result<&Address, Error>; + fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>; + fn get_billing_phone(&self) -> Result<&PhoneDetails, Error>; + fn get_description(&self) -> Result<String, Error>; + fn get_return_url(&self) -> Result<String, Error>; + fn get_billing_address(&self) -> Result<&AddressDetails, Error>; + fn get_shipping_address(&self) -> Result<&AddressDetails, Error>; + fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error>; + fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>; + fn get_session_token(&self) -> Result<String, Error>; + fn get_billing_first_name(&self) -> Result<Secret<String>, Error>; + fn get_billing_full_name(&self) -> Result<Secret<String>, Error>; + fn get_billing_last_name(&self) -> Result<Secret<String>, Error>; + fn get_billing_line1(&self) -> Result<Secret<String>, Error>; + fn get_billing_city(&self) -> Result<String, Error>; + fn get_billing_email(&self) -> Result<Email, Error>; + fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>; + fn to_connector_meta<T>(&self) -> Result<T, Error> + where + T: serde::de::DeserializeOwned; + fn is_three_ds(&self) -> bool; + fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error>; + fn get_customer_id(&self) -> Result<id_type::CustomerId, 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_models::payouts::PayoutMethodData, Error>; + #[cfg(feature = "payouts")] + fn get_quote_id(&self) -> Result<String, Error>; + + fn get_optional_billing(&self) -> Option<&Address>; + fn get_optional_shipping(&self) -> Option<&Address>; + fn get_optional_shipping_line1(&self) -> Option<Secret<String>>; + fn get_optional_shipping_line2(&self) -> Option<Secret<String>>; + fn get_optional_shipping_city(&self) -> Option<String>; + fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>; + fn get_optional_shipping_zip(&self) -> Option<Secret<String>>; + fn get_optional_shipping_state(&self) -> Option<Secret<String>>; + fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>; + fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>; + fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>; + fn get_optional_shipping_email(&self) -> Option<Email>; + + fn get_optional_billing_full_name(&self) -> Option<Secret<String>>; + fn get_optional_billing_line1(&self) -> Option<Secret<String>>; + fn get_optional_billing_line2(&self) -> Option<Secret<String>>; + fn get_optional_billing_city(&self) -> Option<String>; + fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>; + fn get_optional_billing_zip(&self) -> Option<Secret<String>>; + fn get_optional_billing_state(&self) -> Option<Secret<String>>; + fn get_optional_billing_first_name(&self) -> Option<Secret<String>>; + fn get_optional_billing_last_name(&self) -> Option<Secret<String>>; + fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>; + fn get_optional_billing_email(&self) -> Option<Email>; +} + +impl<Flow, Request, Response> RouterData + for hyperswitch_domain_models::router_data::RouterData<Flow, Request, Response> +{ + fn get_billing(&self) -> Result<&Address, Error> { + self.address + .get_payment_method_billing() + .ok_or_else(missing_field_err("billing")) + } + + fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error> { + self.address + .get_payment_method_billing() + .and_then(|a| a.address.as_ref()) + .and_then(|ad| ad.country) + .ok_or_else(missing_field_err( + "payment_method_data.billing.address.country", + )) + } + + fn get_billing_phone(&self) -> Result<&PhoneDetails, Error> { + self.address + .get_payment_method_billing() + .and_then(|a| a.phone.as_ref()) + .ok_or_else(missing_field_err("billing.phone")) + } + + fn get_optional_billing(&self) -> Option<&Address> { + self.address.get_payment_method_billing() + } + + fn get_optional_shipping(&self) -> Option<&Address> { + self.address.get_shipping() + } + + fn get_optional_shipping_first_name(&self) -> Option<Secret<String>> { + self.address.get_shipping().and_then(|shipping_address| { + shipping_address + .clone() + .address + .and_then(|shipping_details| shipping_details.first_name) + }) + } + + fn get_optional_shipping_last_name(&self) -> Option<Secret<String>> { + self.address.get_shipping().and_then(|shipping_address| { + shipping_address + .clone() + .address + .and_then(|shipping_details| shipping_details.last_name) + }) + } + + fn get_optional_shipping_line1(&self) -> Option<Secret<String>> { + self.address.get_shipping().and_then(|shipping_address| { + shipping_address + .clone() + .address + .and_then(|shipping_details| shipping_details.line1) + }) + } + + fn get_optional_shipping_line2(&self) -> Option<Secret<String>> { + self.address.get_shipping().and_then(|shipping_address| { + shipping_address + .clone() + .address + .and_then(|shipping_details| shipping_details.line2) + }) + } + + fn get_optional_shipping_city(&self) -> Option<String> { + self.address.get_shipping().and_then(|shipping_address| { + shipping_address + .clone() + .address + .and_then(|shipping_details| shipping_details.city) + }) + } + + fn get_optional_shipping_state(&self) -> Option<Secret<String>> { + self.address.get_shipping().and_then(|shipping_address| { + shipping_address + .clone() + .address + .and_then(|shipping_details| shipping_details.state) + }) + } + + fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2> { + self.address.get_shipping().and_then(|shipping_address| { + shipping_address + .clone() + .address + .and_then(|shipping_details| shipping_details.country) + }) + } + + fn get_optional_shipping_zip(&self) -> Option<Secret<String>> { + self.address.get_shipping().and_then(|shipping_address| { + shipping_address + .clone() + .address + .and_then(|shipping_details| shipping_details.zip) + }) + } + + fn get_optional_shipping_email(&self) -> Option<Email> { + self.address + .get_shipping() + .and_then(|shipping_address| shipping_address.clone().email) + } + + fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>> { + self.address + .get_shipping() + .and_then(|shipping_address| shipping_address.clone().phone) + .and_then(|phone_details| phone_details.get_number_with_country_code().ok()) + } + + fn get_description(&self) -> Result<String, Error> { + self.description + .clone() + .ok_or_else(missing_field_err("description")) + } + fn get_return_url(&self) -> Result<String, Error> { + self.return_url + .clone() + .ok_or_else(missing_field_err("return_url")) + } + fn get_billing_address(&self) -> Result<&AddressDetails, Error> { + self.address + .get_payment_method_billing() + .as_ref() + .and_then(|a| a.address.as_ref()) + .ok_or_else(missing_field_err("billing.address")) + } + + fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error> { + self.connector_meta_data + .clone() + .ok_or_else(missing_field_err("connector_meta_data")) + } + + fn get_session_token(&self) -> Result<String, Error> { + self.session_token + .clone() + .ok_or_else(missing_field_err("session_token")) + } + + fn get_billing_first_name(&self) -> Result<Secret<String>, Error> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.first_name.clone()) + }) + .ok_or_else(missing_field_err( + "payment_method_data.billing.address.first_name", + )) + } + + fn get_billing_full_name(&self) -> Result<Secret<String>, Error> { + self.get_optional_billing() + .and_then(|billing_details| billing_details.address.as_ref()) + .and_then(|billing_address| billing_address.get_optional_full_name()) + .ok_or_else(missing_field_err( + "payment_method_data.billing.address.first_name", + )) + } + + fn get_billing_last_name(&self) -> Result<Secret<String>, Error> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.last_name.clone()) + }) + .ok_or_else(missing_field_err( + "payment_method_data.billing.address.last_name", + )) + } + + fn get_billing_line1(&self) -> Result<Secret<String>, Error> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.line1.clone()) + }) + .ok_or_else(missing_field_err( + "payment_method_data.billing.address.line1", + )) + } + fn get_billing_city(&self) -> Result<String, Error> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.city) + }) + .ok_or_else(missing_field_err( + "payment_method_data.billing.address.city", + )) + } + + fn get_billing_email(&self) -> Result<Email, Error> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| billing_address.email.clone()) + .ok_or_else(missing_field_err("payment_method_data.billing.email")) + } + + fn get_billing_phone_number(&self) -> Result<Secret<String>, Error> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| billing_address.clone().phone) + .map(|phone_details| phone_details.get_number_with_country_code()) + .transpose()? + .ok_or_else(missing_field_err("payment_method_data.billing.phone")) + } + + fn get_optional_billing_line1(&self) -> Option<Secret<String>> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.line1) + }) + } + + fn get_optional_billing_line2(&self) -> Option<Secret<String>> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.line2) + }) + } + + fn get_optional_billing_city(&self) -> Option<String> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.city) + }) + } + + fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.country) + }) + } + + fn get_optional_billing_zip(&self) -> Option<Secret<String>> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.zip) + }) + } + + fn get_optional_billing_state(&self) -> Option<Secret<String>> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.state) + }) + } + + fn get_optional_billing_first_name(&self) -> Option<Secret<String>> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.first_name) + }) + } + + fn get_optional_billing_last_name(&self) -> Option<Secret<String>> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .address + .and_then(|billing_details| billing_details.last_name) + }) + } + + fn get_optional_billing_phone_number(&self) -> Option<Secret<String>> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| { + billing_address + .clone() + .phone + .and_then(|phone_data| phone_data.number) + }) + } + + fn get_optional_billing_email(&self) -> Option<Email> { + self.address + .get_payment_method_billing() + .and_then(|billing_address| billing_address.clone().email) + } + fn to_connector_meta<T>(&self) -> Result<T, Error> + where + T: serde::de::DeserializeOwned, + { + self.get_connector_meta()? + .parse_value(std::any::type_name::<T>()) + .change_context(errors::ConnectorError::NoConnectorMetaData) + } + + fn is_three_ds(&self) -> bool { + matches!(self.auth_type, enums::AuthenticationType::ThreeDs) + } + + fn get_shipping_address(&self) -> Result<&AddressDetails, Error> { + self.address + .get_shipping() + .and_then(|a| a.address.as_ref()) + .ok_or_else(missing_field_err("shipping.address")) + } + + fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error> { + self.address + .get_shipping() + .ok_or_else(missing_field_err("shipping")) + } + + fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error> { + self.payment_method_token + .clone() + .ok_or_else(missing_field_err("payment_method_token")) + } + fn get_customer_id(&self) -> Result<id_type::CustomerId, Error> { + self.customer_id + .to_owned() + .ok_or_else(missing_field_err("customer_id")) + } + fn get_connector_customer_id(&self) -> Result<String, Error> { + self.connector_customer + .to_owned() + .ok_or_else(missing_field_err("connector_customer_id")) + } + fn get_preprocessing_id(&self) -> Result<String, Error> { + self.preprocessing_id + .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")) + } + + fn get_optional_billing_full_name(&self) -> Option<Secret<String>> { + self.get_optional_billing() + .and_then(|billing_details| billing_details.address.as_ref()) + .and_then(|billing_address| billing_address.get_optional_full_name()) + } + + #[cfg(feature = "payouts")] + fn get_payout_method_data(&self) -> Result<api_models::payouts::PayoutMethodData, Error> { + self.payout_method_data + .to_owned() + .ok_or_else(missing_field_err("payout_method_data")) + } + #[cfg(feature = "payouts")] + fn get_quote_id(&self) -> Result<String, Error> { + self.quote_id + .to_owned() + .ok_or_else(missing_field_err("quote_id")) + } +} + +pub trait CardData { + fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>; + fn get_card_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Result<Secret<String>, errors::ConnectorError>; + fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>; + fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>; + fn get_expiry_year_4_digit(&self) -> Secret<String>; + fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>; + fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>; + fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>; +} + +impl CardData for Card { + fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { + let binding = self.card_exp_year.clone(); + let year = binding.peek(); + Ok(Secret::new( + year.get(year.len() - 2..) + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(), + )) + } + fn get_card_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?; + Ok(Secret::new(format!( + "{}{}{}", + self.card_exp_month.peek(), + delimiter, + year.peek() + ))) + } + fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { + let year = self.get_expiry_year_4_digit(); + Secret::new(format!( + "{}{}{}", + year.peek(), + delimiter, + self.card_exp_month.peek() + )) + } + fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { + let year = self.get_expiry_year_4_digit(); + Secret::new(format!( + "{}{}{}", + self.card_exp_month.peek(), + delimiter, + year.peek() + )) + } + fn get_expiry_year_4_digit(&self) -> Secret<String> { + let mut year = self.card_exp_year.peek().clone(); + if year.len() == 2 { + year = format!("20{}", year); + } + Secret::new(year) + } + fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?.expose(); + let month = self.card_exp_month.clone().expose(); + Ok(Secret::new(format!("{year}{month}"))) + } + fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { + self.card_exp_month + .peek() + .clone() + .parse::<i8>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } + fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { + self.card_exp_year + .peek() + .clone() + .parse::<i32>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } +} + +pub trait AddressDetailsData { + fn get_first_name(&self) -> Result<&Secret<String>, Error>; + fn get_last_name(&self) -> Result<&Secret<String>, Error>; + fn get_full_name(&self) -> Result<Secret<String>, Error>; + fn get_line1(&self) -> Result<&Secret<String>, Error>; + fn get_city(&self) -> Result<&String, Error>; + fn get_line2(&self) -> Result<&Secret<String>, Error>; + fn get_state(&self) -> Result<&Secret<String>, Error>; + fn get_zip(&self) -> Result<&Secret<String>, Error>; + fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error>; + fn get_combined_address_line(&self) -> Result<Secret<String>, Error>; + fn get_optional_line2(&self) -> Option<Secret<String>>; +} + +impl AddressDetailsData for AddressDetails { + fn get_first_name(&self) -> Result<&Secret<String>, Error> { + self.first_name + .as_ref() + .ok_or_else(missing_field_err("address.first_name")) + } + + fn get_last_name(&self) -> Result<&Secret<String>, Error> { + self.last_name + .as_ref() + .ok_or_else(missing_field_err("address.last_name")) + } + + fn get_full_name(&self) -> Result<Secret<String>, Error> { + let first_name = self.get_first_name()?.peek().to_owned(); + let last_name = self + .get_last_name() + .ok() + .cloned() + .unwrap_or(Secret::new("".to_string())); + let last_name = last_name.peek(); + let full_name = format!("{} {}", first_name, last_name).trim().to_string(); + Ok(Secret::new(full_name)) + } + + fn get_line1(&self) -> Result<&Secret<String>, Error> { + self.line1 + .as_ref() + .ok_or_else(missing_field_err("address.line1")) + } + + fn get_city(&self) -> Result<&String, Error> { + self.city + .as_ref() + .ok_or_else(missing_field_err("address.city")) + } + + fn get_state(&self) -> Result<&Secret<String>, Error> { + self.state + .as_ref() + .ok_or_else(missing_field_err("address.state")) + } + + fn get_line2(&self) -> Result<&Secret<String>, Error> { + self.line2 + .as_ref() + .ok_or_else(missing_field_err("address.line2")) + } + + fn get_zip(&self) -> Result<&Secret<String>, Error> { + self.zip + .as_ref() + .ok_or_else(missing_field_err("address.zip")) + } + + fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error> { + self.country + .as_ref() + .ok_or_else(missing_field_err("address.country")) + } + + fn get_combined_address_line(&self) -> Result<Secret<String>, Error> { + Ok(Secret::new(format!( + "{},{}", + self.get_line1()?.peek(), + self.get_line2()?.peek() + ))) + } + + fn get_optional_line2(&self) -> Option<Secret<String>> { + self.line2.clone() + } +} + +pub trait PhoneDetailsData { + fn get_number(&self) -> Result<Secret<String>, Error>; + fn get_country_code(&self) -> Result<String, Error>; + fn get_number_with_country_code(&self) -> Result<Secret<String>, Error>; + fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error>; + fn extract_country_code(&self) -> Result<String, Error>; +} + +impl PhoneDetailsData for PhoneDetails { + fn get_country_code(&self) -> Result<String, Error> { + self.country_code + .clone() + .ok_or_else(missing_field_err("billing.phone.country_code")) + } + fn extract_country_code(&self) -> Result<String, Error> { + self.get_country_code() + .map(|cc| cc.trim_start_matches('+').to_string()) + } + fn get_number(&self) -> Result<Secret<String>, Error> { + self.number + .clone() + .ok_or_else(missing_field_err("billing.phone.number")) + } + fn get_number_with_country_code(&self) -> Result<Secret<String>, Error> { + let number = self.get_number()?; + let country_code = self.get_country_code()?; + Ok(Secret::new(format!("{}{}", country_code, number.peek()))) + } + fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error> { + let number = self.get_number()?; + let country_code = self.get_country_code()?; + let number_without_plus = country_code.trim_start_matches('+'); + Ok(Secret::new(format!( + "{}#{}", + number_without_plus, + number.peek() + ))) + } +} + +pub trait PaymentsAuthorizeRequestData { + fn is_auto_capture(&self) -> Result<bool, Error>; + fn get_email(&self) -> Result<Email, Error>; + fn get_browser_info(&self) -> Result<BrowserInformation, Error>; + fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; + fn get_card(&self) -> Result<Card, Error>; + fn get_return_url(&self) -> Result<String, Error>; + fn connector_mandate_id(&self) -> Option<String>; + fn is_mandate_payment(&self) -> bool; + fn is_customer_initiated_mandate_payment(&self) -> bool; + fn get_webhook_url(&self) -> Result<String, Error>; + fn get_router_return_url(&self) -> Result<String, Error>; + fn is_wallet(&self) -> bool; + fn is_card(&self) -> bool; + fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; + fn get_connector_mandate_id(&self) -> Result<String, Error>; + fn get_complete_authorize_url(&self) -> Result<String, Error>; + fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>; + fn get_original_amount(&self) -> i64; + fn get_surcharge_amount(&self) -> Option<i64>; + fn get_tax_on_surcharge_amount(&self) -> Option<i64>; + fn get_total_surcharge_amount(&self) -> Option<i64>; + fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue>; + fn get_authentication_data(&self) -> Result<AuthenticationData, Error>; +} + +impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { + fn is_auto_capture(&self) -> Result<bool, Error> { + match self.capture_method { + Some(enums::CaptureMethod::Automatic) | None => Ok(true), + Some(enums::CaptureMethod::Manual) => Ok(false), + Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), + } + } + fn get_email(&self) -> Result<Email, Error> { + self.email.clone().ok_or_else(missing_field_err("email")) + } + fn get_browser_info(&self) -> Result<BrowserInformation, Error> { + self.browser_info + .clone() + .ok_or_else(missing_field_err("browser_info")) + } + fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { + self.order_details + .clone() + .ok_or_else(missing_field_err("order_details")) + } + + fn get_card(&self) -> Result<Card, Error> { + match self.payment_method_data.clone() { + PaymentMethodData::Card(card) => Ok(card), + _ => Err(missing_field_err("card")()), + } + } + fn get_return_url(&self) -> Result<String, Error> { + self.router_return_url + .clone() + .ok_or_else(missing_field_err("return_url")) + } + + fn get_complete_authorize_url(&self) -> Result<String, Error> { + self.complete_authorize_url + .clone() + .ok_or_else(missing_field_err("complete_authorize_url")) + } + + fn connector_mandate_id(&self) -> Option<String> { + self.mandate_id + .as_ref() + .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { + Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { + connector_mandate_ids.connector_mandate_id.clone() + } + Some(payments::MandateReferenceId::NetworkMandateId(_)) | None => None, + }) + } + fn is_mandate_payment(&self) -> bool { + ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) + && self.setup_future_usage.map_or(false, |setup_future_usage| { + setup_future_usage == FutureUsage::OffSession + })) + || self + .mandate_id + .as_ref() + .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) + .is_some() + } + fn get_webhook_url(&self) -> Result<String, Error> { + self.webhook_url + .clone() + .ok_or_else(missing_field_err("webhook_url")) + } + fn get_router_return_url(&self) -> Result<String, Error> { + self.router_return_url + .clone() + .ok_or_else(missing_field_err("return_url")) + } + fn is_wallet(&self) -> bool { + matches!(self.payment_method_data, PaymentMethodData::Wallet(_)) + } + fn is_card(&self) -> bool { + matches!(self.payment_method_data, PaymentMethodData::Card(_)) + } + + fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { + self.payment_method_type + .to_owned() + .ok_or_else(missing_field_err("payment_method_type")) + } + + fn get_connector_mandate_id(&self) -> Result<String, Error> { + self.connector_mandate_id() + .ok_or_else(missing_field_err("connector_mandate_id")) + } + fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>> { + self.browser_info.clone().and_then(|browser_info| { + browser_info + .ip_address + .map(|ip| Secret::new(ip.to_string())) + }) + } + fn get_original_amount(&self) -> i64 { + self.surcharge_details + .as_ref() + .map(|surcharge_details| surcharge_details.original_amount.get_amount_as_i64()) + .unwrap_or(self.amount) + } + fn get_surcharge_amount(&self) -> Option<i64> { + self.surcharge_details + .as_ref() + .map(|surcharge_details| surcharge_details.surcharge_amount.get_amount_as_i64()) + } + fn get_tax_on_surcharge_amount(&self) -> Option<i64> { + self.surcharge_details.as_ref().map(|surcharge_details| { + surcharge_details + .tax_on_surcharge_amount + .get_amount_as_i64() + }) + } + fn get_total_surcharge_amount(&self) -> Option<i64> { + self.surcharge_details.as_ref().map(|surcharge_details| { + surcharge_details + .get_total_surcharge_amount() + .get_amount_as_i64() + }) + } + + fn is_customer_initiated_mandate_payment(&self) -> bool { + (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) + && self.setup_future_usage.map_or(false, |setup_future_usage| { + setup_future_usage == FutureUsage::OffSession + }) + } + + fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> { + self.metadata.clone().and_then(|meta_data| match meta_data { + serde_json::Value::Null + | serde_json::Value::Bool(_) + | serde_json::Value::Number(_) + | serde_json::Value::String(_) + | serde_json::Value::Array(_) => None, + serde_json::Value::Object(_) => Some(meta_data.into()), + }) + } + + fn get_authentication_data(&self) -> Result<AuthenticationData, Error> { + self.authentication_data + .clone() + .ok_or_else(missing_field_err("authentication_data")) + } +} + +pub trait PaymentsCaptureRequestData { + fn is_multiple_capture(&self) -> bool; + fn get_browser_info(&self) -> Result<BrowserInformation, Error>; +} + +impl PaymentsCaptureRequestData for PaymentsCaptureData { + fn is_multiple_capture(&self) -> bool { + self.multiple_capture_data.is_some() + } + fn get_browser_info(&self) -> Result<BrowserInformation, Error> { + self.browser_info + .clone() + .ok_or_else(missing_field_err("browser_info")) + } +} + +pub trait PaymentsCancelRequestData { + fn get_amount(&self) -> Result<i64, Error>; + fn get_currency(&self) -> Result<enums::Currency, Error>; + fn get_cancellation_reason(&self) -> Result<String, Error>; + fn get_browser_info(&self) -> Result<BrowserInformation, Error>; +} + +impl PaymentsCancelRequestData for PaymentsCancelData { + fn get_amount(&self) -> Result<i64, Error> { + self.amount.ok_or_else(missing_field_err("amount")) + } + fn get_currency(&self) -> Result<enums::Currency, Error> { + self.currency.ok_or_else(missing_field_err("currency")) + } + fn get_cancellation_reason(&self) -> Result<String, Error> { + self.cancellation_reason + .clone() + .ok_or_else(missing_field_err("cancellation_reason")) + } + fn get_browser_info(&self) -> Result<BrowserInformation, Error> { + self.browser_info + .clone() + .ok_or_else(missing_field_err("browser_info")) + } +} + +pub trait RefundsRequestData { + fn get_connector_refund_id(&self) -> Result<String, Error>; + fn get_webhook_url(&self) -> Result<String, Error>; + fn get_browser_info(&self) -> Result<BrowserInformation, Error>; +} + +impl RefundsRequestData for RefundsData { + #[track_caller] + fn get_connector_refund_id(&self) -> Result<String, Error> { + self.connector_refund_id + .clone() + .get_required_value("connector_refund_id") + .change_context(errors::ConnectorError::MissingConnectorTransactionID) + } + fn get_webhook_url(&self) -> Result<String, Error> { + self.webhook_url + .clone() + .ok_or_else(missing_field_err("webhook_url")) + } + fn get_browser_info(&self) -> Result<BrowserInformation, Error> { + self.browser_info + .clone() + .ok_or_else(missing_field_err("browser_info")) + } +} + +pub trait PaymentsSetupMandateRequestData { + fn get_browser_info(&self) -> Result<BrowserInformation, Error>; + fn get_email(&self) -> Result<Email, Error>; + fn is_card(&self) -> bool; +} + +impl PaymentsSetupMandateRequestData for SetupMandateRequestData { + fn get_browser_info(&self) -> Result<BrowserInformation, Error> { + self.browser_info + .clone() + .ok_or_else(missing_field_err("browser_info")) + } + fn get_email(&self) -> Result<Email, Error> { + self.email.clone().ok_or_else(missing_field_err("email")) + } + fn is_card(&self) -> bool { + matches!(self.payment_method_data, PaymentMethodData::Card(_)) + } +} + +pub trait BrowserInformationData { + fn get_accept_header(&self) -> Result<String, Error>; + fn get_language(&self) -> Result<String, Error>; + fn get_screen_height(&self) -> Result<u32, Error>; + fn get_screen_width(&self) -> Result<u32, Error>; + fn get_color_depth(&self) -> Result<u8, Error>; + fn get_user_agent(&self) -> Result<String, Error>; + fn get_time_zone(&self) -> Result<i32, Error>; + fn get_java_enabled(&self) -> Result<bool, Error>; + fn get_java_script_enabled(&self) -> Result<bool, Error>; + fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>; +} + +impl BrowserInformationData for BrowserInformation { + fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> { + let ip_address = self + .ip_address + .ok_or_else(missing_field_err("browser_info.ip_address"))?; + Ok(Secret::new(ip_address.to_string())) + } + fn get_accept_header(&self) -> Result<String, Error> { + self.accept_header + .clone() + .ok_or_else(missing_field_err("browser_info.accept_header")) + } + fn get_language(&self) -> Result<String, Error> { + self.language + .clone() + .ok_or_else(missing_field_err("browser_info.language")) + } + fn get_screen_height(&self) -> Result<u32, Error> { + self.screen_height + .ok_or_else(missing_field_err("browser_info.screen_height")) + } + fn get_screen_width(&self) -> Result<u32, Error> { + self.screen_width + .ok_or_else(missing_field_err("browser_info.screen_width")) + } + fn get_color_depth(&self) -> Result<u8, Error> { + self.color_depth + .ok_or_else(missing_field_err("browser_info.color_depth")) + } + fn get_user_agent(&self) -> Result<String, Error> { + self.user_agent + .clone() + .ok_or_else(missing_field_err("browser_info.user_agent")) + } + fn get_time_zone(&self) -> Result<i32, Error> { + self.time_zone + .ok_or_else(missing_field_err("browser_info.time_zone")) + } + fn get_java_enabled(&self) -> Result<bool, Error> { + self.java_enabled + .ok_or_else(missing_field_err("browser_info.java_enabled")) + } + fn get_java_script_enabled(&self) -> Result<bool, Error> { + self.java_script_enabled + .ok_or_else(missing_field_err("browser_info.java_script_enabled")) + } +} diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index 2ce3ecca536..d10d72ab3ad 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license.workspace = true [features] -default = ["olap", "payouts", "frm", "v1"] +default = ["olap", "frm", "v1"] encryption_service = [] olap = [] payouts = ["api_models/payouts"] diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 387c024df18..c48f721b210 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -17,6 +17,7 @@ pub mod router_response_types; pub mod behaviour; pub mod merchant_key_store; pub mod type_encryption; +pub mod types; #[cfg(not(feature = "payouts"))] pub trait PayoutAttemptInterface {} diff --git a/crates/hyperswitch_domain_models/src/router_flow_types.rs b/crates/hyperswitch_domain_models/src/router_flow_types.rs index 065b5f0f40b..6cdde87772b 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types.rs @@ -2,6 +2,7 @@ pub mod access_token_auth; pub mod dispute; pub mod files; pub mod fraud_check; +pub mod mandate_revoke; pub mod payments; pub mod payouts; pub mod refunds; diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs b/crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs new file mode 100644 index 00000000000..1c8f750ceef --- /dev/null +++ b/crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs @@ -0,0 +1,2 @@ +#[derive(Clone, Debug)] +pub struct MandateRevoke; diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs new file mode 100644 index 00000000000..814d235e6f0 --- /dev/null +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -0,0 +1,19 @@ +use crate::{ + router_data::RouterData, + router_flow_types::{Authorize, Capture, PSync, RSync, SetupMandate, Void}, + router_request_types::{ + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; + +pub type PaymentsAuthorizeRouterData = + RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; +pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; +pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; +pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; +pub type SetupMandateRouterData = + RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; +pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; +pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml index 05d5987abae..7830415e5d8 100644 --- a/crates/hyperswitch_interfaces/Cargo.toml +++ b/crates/hyperswitch_interfaces/Cargo.toml @@ -7,9 +7,10 @@ readme = "README.md" license.workspace = true [features] -default = ["dummy_connector", "payouts"] +default = ["dummy_connector", "frm", "payouts"] dummy_connector = [] -payouts = [] +payouts = ["hyperswitch_domain_models/payouts"] +frm = ["hyperswitch_domain_models/frm"] [dependencies] actix-web = "4.5.1" @@ -23,6 +24,7 @@ once_cell = "1.19.0" reqwest = "0.11.27" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" +strum = { version = "0.26", features = ["derive"] } thiserror = "1.0.58" time = "0.3.35" diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs index 30dad9acb98..82ae0d141d7 100644 --- a/crates/hyperswitch_interfaces/src/api.rs +++ b/crates/hyperswitch_interfaces/src/api.rs @@ -1,16 +1,48 @@ //! API interface +pub mod disputes; +pub mod disputes_v2; +pub mod files; +pub mod files_v2; +#[cfg(feature = "frm")] +pub mod fraud_check; +#[cfg(feature = "frm")] +pub mod fraud_check_v2; +pub mod payments; +pub mod payments_v2; +#[cfg(feature = "payouts")] +pub mod payouts; +#[cfg(feature = "payouts")] +pub mod payouts_v2; +pub mod refunds; +pub mod refunds_v2; + +use common_enums::enums::{CaptureMethod, PaymentMethodType}; use common_utils::{ errors::CustomResult, request::{Method, Request, RequestContent}, }; -use hyperswitch_domain_models::router_data::{ConnectorAuthType, ErrorResponse, RouterData}; +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_data_v2::{ + flow_common_types::WebhookSourceVerifyData, AccessTokenFlowData, MandateRevokeFlowData, + }, + router_flow_types::{mandate_revoke::MandateRevoke, AccessTokenAuth, VerifyWebhookSource}, + router_request_types::{ + AccessTokenRequestData, MandateRevokeRequestData, VerifyWebhookSourceRequestData, + }, + router_response_types::{MandateRevokeResponseData, VerifyWebhookSourceResponseData}, +}; use masking::Maskable; use router_env::metrics::add_attributes; use serde_json::json; +pub use self::{payments::*, refunds::*}; use crate::{ - configs::Connectors, consts, errors, events::connector_api_logs::ConnectorEvent, metrics, types, + configs::Connectors, connector_integration_v2::ConnectorIntegrationV2, consts, errors, + events::connector_api_logs::ConnectorEvent, metrics, types, }; /// type BoxedConnectorIntegration @@ -254,3 +286,115 @@ pub trait ConnectorCommonExt<Flow, Req, Resp>: Ok(Vec::new()) } } + +/// trait ConnectorMandateRevoke +pub trait ConnectorMandateRevoke: + ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> +{ +} + +/// trait ConnectorMandateRevokeV2 +pub trait ConnectorMandateRevokeV2: + ConnectorIntegrationV2< + MandateRevoke, + MandateRevokeFlowData, + MandateRevokeRequestData, + MandateRevokeResponseData, +> +{ +} + +/// trait ConnectorAccessToken +pub trait ConnectorAccessToken: + ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> +{ +} + +/// trait ConnectorAccessTokenV2 +pub trait ConnectorAccessTokenV2: + ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken> +{ +} + +/// trait ConnectorVerifyWebhookSource +pub trait ConnectorVerifyWebhookSource: + ConnectorIntegration< + VerifyWebhookSource, + VerifyWebhookSourceRequestData, + VerifyWebhookSourceResponseData, +> +{ +} + +/// trait ConnectorVerifyWebhookSourceV2 +pub trait ConnectorVerifyWebhookSourceV2: + ConnectorIntegrationV2< + VerifyWebhookSource, + WebhookSourceVerifyData, + VerifyWebhookSourceRequestData, + VerifyWebhookSourceResponseData, +> +{ +} + +/// trait ConnectorValidation +pub trait ConnectorValidation: ConnectorCommon { + /// fn validate_capture_method + fn validate_capture_method( + &self, + capture_method: Option<CaptureMethod>, + _pmt: Option<PaymentMethodType>, + ) -> CustomResult<(), errors::ConnectorError> { + let capture_method = capture_method.unwrap_or_default(); + match capture_method { + CaptureMethod::Automatic => Ok(()), + CaptureMethod::Manual | CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => { + Err(errors::ConnectorError::NotSupported { + message: capture_method.to_string(), + connector: self.id(), + } + .into()) + } + } + } + + /// fn validate_mandate_payment + fn validate_mandate_payment( + &self, + pm_type: Option<PaymentMethodType>, + _pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + let connector = self.id(); + match pm_type { + Some(pm_type) => Err(errors::ConnectorError::NotSupported { + message: format!("{} mandate payment", pm_type), + connector, + } + .into()), + None => Err(errors::ConnectorError::NotSupported { + message: " mandate payment".to_string(), + connector, + } + .into()), + } + } + + /// fn validate_psync_reference_id + fn validate_psync_reference_id( + &self, + data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _is_three_ds: bool, + _status: common_enums::enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + data.connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID) + .map(|_| ()) + } + + /// fn is_webhook_source_verification_mandatory + fn is_webhook_source_verification_mandatory(&self) -> bool { + false + } +} diff --git a/crates/hyperswitch_interfaces/src/api/disputes.rs b/crates/hyperswitch_interfaces/src/api/disputes.rs new file mode 100644 index 00000000000..3ff5d6fb957 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/disputes.rs @@ -0,0 +1,32 @@ +//! Disputes interface + +use hyperswitch_domain_models::{ + router_flow_types::dispute::{Accept, Defend, Evidence}, + router_request_types::{ + AcceptDisputeRequestData, DefendDisputeRequestData, SubmitEvidenceRequestData, + }, + router_response_types::{AcceptDisputeResponse, DefendDisputeResponse, SubmitEvidenceResponse}, +}; + +use crate::api::ConnectorIntegration; + +/// trait AcceptDispute +pub trait AcceptDispute: + ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> +{ +} + +/// trait SubmitEvidence +pub trait SubmitEvidence: + ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> +{ +} + +/// trait DefendDispute +pub trait DefendDispute: + ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> +{ +} + +/// trait Dispute +pub trait Dispute: super::ConnectorCommon + AcceptDispute + SubmitEvidence + DefendDispute {} diff --git a/crates/hyperswitch_interfaces/src/api/disputes_v2.rs b/crates/hyperswitch_interfaces/src/api/disputes_v2.rs new file mode 100644 index 00000000000..b038b141d94 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/disputes_v2.rs @@ -0,0 +1,40 @@ +//! Disputes V2 interface +use hyperswitch_domain_models::{ + router_data_v2::DisputesFlowData, + router_flow_types::dispute::{Accept, Defend, Evidence}, + router_request_types::{ + AcceptDisputeRequestData, DefendDisputeRequestData, SubmitEvidenceRequestData, + }, + router_response_types::{AcceptDisputeResponse, DefendDisputeResponse, SubmitEvidenceResponse}, +}; + +use crate::api::ConnectorIntegrationV2; + +/// trait AcceptDisputeV2 +pub trait AcceptDisputeV2: + ConnectorIntegrationV2<Accept, DisputesFlowData, AcceptDisputeRequestData, AcceptDisputeResponse> +{ +} + +/// trait SubmitEvidenceV2 +pub trait SubmitEvidenceV2: + ConnectorIntegrationV2< + Evidence, + DisputesFlowData, + SubmitEvidenceRequestData, + SubmitEvidenceResponse, +> +{ +} + +/// trait DefendDisputeV2 +pub trait DefendDisputeV2: + ConnectorIntegrationV2<Defend, DisputesFlowData, DefendDisputeRequestData, DefendDisputeResponse> +{ +} + +/// trait DisputeV2 +pub trait DisputeV2: + super::ConnectorCommon + AcceptDisputeV2 + SubmitEvidenceV2 + DefendDisputeV2 +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/files.rs b/crates/hyperswitch_interfaces/src/api/files.rs new file mode 100644 index 00000000000..7cee6b9f4ce --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/files.rs @@ -0,0 +1,49 @@ +//! Files interface + +use hyperswitch_domain_models::{ + router_flow_types::files::{Retrieve, Upload}, + router_request_types::{RetrieveFileRequestData, UploadFileRequestData}, + router_response_types::{RetrieveFileResponse, UploadFileResponse}, +}; + +use crate::{ + api::{ConnectorCommon, ConnectorIntegration}, + errors, +}; + +/// enum FilePurpose +#[derive(Debug, serde::Deserialize, strum::Display, Clone, serde::Serialize)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum FilePurpose { + /// DisputeEvidence + DisputeEvidence, +} + +/// trait UploadFile +pub trait UploadFile: + ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> +{ +} + +/// trait RetrieveFile +pub trait RetrieveFile: + ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> +{ +} + +/// trait FileUpload +pub trait FileUpload: ConnectorCommon + Sync + UploadFile + RetrieveFile { + /// fn validate_file_upload + fn validate_file_upload( + &self, + _purpose: FilePurpose, + _file_size: i32, + _file_type: mime::Mime, + ) -> common_utils::errors::CustomResult<(), errors::ConnectorError> { + Err(errors::ConnectorError::FileValidationFailed { + reason: "".to_owned(), + } + .into()) + } +} diff --git a/crates/hyperswitch_interfaces/src/api/files_v2.rs b/crates/hyperswitch_interfaces/src/api/files_v2.rs new file mode 100644 index 00000000000..ba8336b9730 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/files_v2.rs @@ -0,0 +1,38 @@ +//! Files V2 interface + +use hyperswitch_domain_models::{ + router_data_v2::FilesFlowData, + router_flow_types::{Retrieve, Upload}, + router_request_types::{RetrieveFileRequestData, UploadFileRequestData}, + router_response_types::{RetrieveFileResponse, UploadFileResponse}, +}; + +use crate::api::{errors, files::FilePurpose, ConnectorCommon, ConnectorIntegrationV2}; + +/// trait UploadFileV2 +pub trait UploadFileV2: + ConnectorIntegrationV2<Upload, FilesFlowData, UploadFileRequestData, UploadFileResponse> +{ +} + +/// trait RetrieveFileV2 +pub trait RetrieveFileV2: + ConnectorIntegrationV2<Retrieve, FilesFlowData, RetrieveFileRequestData, RetrieveFileResponse> +{ +} + +/// trait FileUploadV2 +pub trait FileUploadV2: ConnectorCommon + Sync + UploadFileV2 + RetrieveFileV2 { + /// fn validate_file_upload_v2 + fn validate_file_upload_v2( + &self, + _purpose: FilePurpose, + _file_size: i32, + _file_type: mime::Mime, + ) -> common_utils::errors::CustomResult<(), errors::ConnectorError> { + Err(errors::ConnectorError::FileValidationFailed { + reason: "".to_owned(), + } + .into()) + } +} diff --git a/crates/hyperswitch_interfaces/src/api/fraud_check.rs b/crates/hyperswitch_interfaces/src/api/fraud_check.rs new file mode 100644 index 00000000000..5bee65c8d97 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/fraud_check.rs @@ -0,0 +1,41 @@ +//! FRM interface +use hyperswitch_domain_models::{ + router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; + +use crate::api::ConnectorIntegration; + +/// trait FraudCheckSale +pub trait FraudCheckSale: + ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> +{ +} + +/// trait FraudCheckCheckout +pub trait FraudCheckCheckout: + ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> +{ +} + +/// trait FraudCheckTransaction +pub trait FraudCheckTransaction: + ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> +{ +} + +/// trait FraudCheckFulfillment +pub trait FraudCheckFulfillment: + ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> +{ +} + +/// trait FraudCheckRecordReturn +pub trait FraudCheckRecordReturn: + ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs b/crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs new file mode 100644 index 00000000000..f5492909500 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs @@ -0,0 +1,47 @@ +//! FRM V2 interface +use hyperswitch_domain_models::{ + router_data_v2::flow_common_types::FrmFlowData, + router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; + +use crate::api::ConnectorIntegrationV2; + +/// trait FraudCheckSaleV2 +pub trait FraudCheckSaleV2: + ConnectorIntegrationV2<Sale, FrmFlowData, FraudCheckSaleData, FraudCheckResponseData> +{ +} + +/// trait FraudCheckCheckoutV2 +pub trait FraudCheckCheckoutV2: + ConnectorIntegrationV2<Checkout, FrmFlowData, FraudCheckCheckoutData, FraudCheckResponseData> +{ +} + +/// trait FraudCheckTransactionV2 +pub trait FraudCheckTransactionV2: + ConnectorIntegrationV2<Transaction, FrmFlowData, FraudCheckTransactionData, FraudCheckResponseData> +{ +} + +/// trait FraudCheckFulfillmentV2 +pub trait FraudCheckFulfillmentV2: + ConnectorIntegrationV2<Fulfillment, FrmFlowData, FraudCheckFulfillmentData, FraudCheckResponseData> +{ +} + +/// trait FraudCheckRecordReturnV2 +pub trait FraudCheckRecordReturnV2: + ConnectorIntegrationV2< + RecordReturn, + FrmFlowData, + FraudCheckRecordReturnData, + FraudCheckResponseData, +> +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/payments.rs b/crates/hyperswitch_interfaces/src/api/payments.rs new file mode 100644 index 00000000000..8a53f65805e --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/payments.rs @@ -0,0 +1,135 @@ +//! Payments interface + +use hyperswitch_domain_models::{ + router_flow_types::payments::{ + Approve, Authorize, AuthorizeSessionToken, Capture, CompleteAuthorize, + CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, + PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, + }, + router_request_types::{ + AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, + PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsSessionData, PaymentsSyncData, SetupMandateRequestData, + }, + router_response_types::PaymentsResponseData, +}; + +use crate::api; + +/// trait Payment +pub trait Payment: + api::ConnectorCommon + + api::ConnectorValidation + + PaymentAuthorize + + PaymentAuthorizeSessionToken + + PaymentsCompleteAuthorize + + PaymentSync + + PaymentCapture + + PaymentVoid + + PaymentApprove + + PaymentReject + + MandateSetup + + PaymentSession + + PaymentToken + + PaymentsPreProcessing + + PaymentsPostProcessing + + ConnectorCustomer + + PaymentIncrementalAuthorization +{ +} + +/// trait PaymentSession +pub trait PaymentSession: + api::ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> +{ +} + +/// trait MandateSetup +pub trait MandateSetup: + api::ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> +{ +} + +/// trait PaymentAuthorize +pub trait PaymentAuthorize: + api::ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> +{ +} + +/// trait PaymentCapture +pub trait PaymentCapture: + api::ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> +{ +} + +/// trait PaymentSync +pub trait PaymentSync: + api::ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> +{ +} + +/// trait PaymentVoid +pub trait PaymentVoid: + api::ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> +{ +} + +/// trait PaymentApprove +pub trait PaymentApprove: + api::ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData> +{ +} + +/// trait PaymentReject +pub trait PaymentReject: + api::ConnectorIntegration<Reject, PaymentsRejectData, PaymentsResponseData> +{ +} + +/// trait PaymentToken +pub trait PaymentToken: + api::ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> +{ +} + +/// trait PaymentAuthorizeSessionToken +pub trait PaymentAuthorizeSessionToken: + api::ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> +{ +} + +/// trait PaymentIncrementalAuthorization +pub trait PaymentIncrementalAuthorization: + api::ConnectorIntegration< + IncrementalAuthorization, + PaymentsIncrementalAuthorizationData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentsCompleteAuthorize +pub trait PaymentsCompleteAuthorize: + api::ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> +{ +} + +/// trait ConnectorCustomer +pub trait ConnectorCustomer: + api::ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> +{ +} + +/// trait PaymentsPreProcessing +pub trait PaymentsPreProcessing: + api::ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> +{ +} + +/// trait PaymentsPostProcessing +pub trait PaymentsPostProcessing: + api::ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData> +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/payments_v2.rs b/crates/hyperswitch_interfaces/src/api/payments_v2.rs new file mode 100644 index 00000000000..4ebe9e8517f --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/payments_v2.rs @@ -0,0 +1,167 @@ +//! Payments V2 interface + +use hyperswitch_domain_models::{ + router_data_v2::PaymentFlowData, + router_flow_types::payments::{ + Approve, Authorize, AuthorizeSessionToken, Capture, CompleteAuthorize, + CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, + PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, + }, + router_request_types::{ + AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, + PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsSessionData, PaymentsSyncData, SetupMandateRequestData, + }, + router_response_types::PaymentsResponseData, +}; + +use crate::api::{ConnectorCommon, ConnectorIntegrationV2, ConnectorValidation}; + +/// trait PaymentAuthorizeV2 +pub trait PaymentAuthorizeV2: + ConnectorIntegrationV2<Authorize, PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData> +{ +} + +/// trait PaymentAuthorizeSessionTokenV2 +pub trait PaymentAuthorizeSessionTokenV2: + ConnectorIntegrationV2< + AuthorizeSessionToken, + PaymentFlowData, + AuthorizeSessionTokenData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentSyncV2 +pub trait PaymentSyncV2: + ConnectorIntegrationV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData> +{ +} + +/// trait PaymentVoidV2 +pub trait PaymentVoidV2: + ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData> +{ +} + +/// trait PaymentApproveV2 +pub trait PaymentApproveV2: + ConnectorIntegrationV2<Approve, PaymentFlowData, PaymentsApproveData, PaymentsResponseData> +{ +} + +/// trait PaymentRejectV2 +pub trait PaymentRejectV2: + ConnectorIntegrationV2<Reject, PaymentFlowData, PaymentsRejectData, PaymentsResponseData> +{ +} + +/// trait PaymentCaptureV2 +pub trait PaymentCaptureV2: + ConnectorIntegrationV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData> +{ +} + +/// trait PaymentSessionV2 +pub trait PaymentSessionV2: + ConnectorIntegrationV2<Session, PaymentFlowData, PaymentsSessionData, PaymentsResponseData> +{ +} + +/// trait MandateSetupV2 +pub trait MandateSetupV2: + ConnectorIntegrationV2<SetupMandate, PaymentFlowData, SetupMandateRequestData, PaymentsResponseData> +{ +} + +/// trait PaymentIncrementalAuthorizationV2 +pub trait PaymentIncrementalAuthorizationV2: + ConnectorIntegrationV2< + IncrementalAuthorization, + PaymentFlowData, + PaymentsIncrementalAuthorizationData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentsCompleteAuthorizeV2 +pub trait PaymentsCompleteAuthorizeV2: + ConnectorIntegrationV2< + CompleteAuthorize, + PaymentFlowData, + CompleteAuthorizeData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentTokenV2 +pub trait PaymentTokenV2: + ConnectorIntegrationV2< + PaymentMethodToken, + PaymentFlowData, + PaymentMethodTokenizationData, + PaymentsResponseData, +> +{ +} + +/// trait ConnectorCustomerV2 +pub trait ConnectorCustomerV2: + ConnectorIntegrationV2< + CreateConnectorCustomer, + PaymentFlowData, + ConnectorCustomerData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentsPreProcessingV2 +pub trait PaymentsPreProcessingV2: + ConnectorIntegrationV2< + PreProcessing, + PaymentFlowData, + PaymentsPreProcessingData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentsPostProcessingV2 +pub trait PaymentsPostProcessingV2: + ConnectorIntegrationV2< + PostProcessing, + PaymentFlowData, + PaymentsPostProcessingData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentV2 +pub trait PaymentV2: + ConnectorCommon + + ConnectorValidation + + PaymentAuthorizeV2 + + PaymentAuthorizeSessionTokenV2 + + PaymentsCompleteAuthorizeV2 + + PaymentSyncV2 + + PaymentCaptureV2 + + PaymentVoidV2 + + PaymentApproveV2 + + PaymentRejectV2 + + MandateSetupV2 + + PaymentSessionV2 + + PaymentTokenV2 + + PaymentsPreProcessingV2 + + PaymentsPostProcessingV2 + + ConnectorCustomerV2 + + PaymentIncrementalAuthorizationV2 +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/payouts.rs b/crates/hyperswitch_interfaces/src/api/payouts.rs new file mode 100644 index 00000000000..894f636707a --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/payouts.rs @@ -0,0 +1,44 @@ +//! Payouts interface + +use hyperswitch_domain_models::router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_request_types::PayoutsData, router_response_types::PayoutsResponseData, +}; + +use crate::api::ConnectorIntegration; + +/// trait PayoutCancel +pub trait PayoutCancel: ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> {} + +/// trait PayoutCreate +pub trait PayoutCreate: ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> {} + +/// trait PayoutEligibility +pub trait PayoutEligibility: + ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutFulfill +pub trait PayoutFulfill: ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> {} + +/// trait PayoutQuote +pub trait PayoutQuote: ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> {} + +/// trait PayoutRecipient +pub trait PayoutRecipient: + ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutRecipientAccount +pub trait PayoutRecipientAccount: + ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutSync +pub trait PayoutSync: ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> {} diff --git a/crates/hyperswitch_interfaces/src/api/payouts_v2.rs b/crates/hyperswitch_interfaces/src/api/payouts_v2.rs new file mode 100644 index 00000000000..40e0726ce80 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/payouts_v2.rs @@ -0,0 +1,59 @@ +//! Payouts V2 interface +use hyperswitch_domain_models::router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_data_v2::flow_common_types::PayoutFlowData, router_request_types::PayoutsData, + router_response_types::PayoutsResponseData, +}; + +use crate::api::ConnectorIntegrationV2; + +/// trait PayoutCancelV2 +pub trait PayoutCancelV2: + ConnectorIntegrationV2<PoCancel, PayoutFlowData, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutCreateV2 +pub trait PayoutCreateV2: + ConnectorIntegrationV2<PoCreate, PayoutFlowData, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutEligibilityV2 +pub trait PayoutEligibilityV2: + ConnectorIntegrationV2<PoEligibility, PayoutFlowData, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutFulfillV2 +pub trait PayoutFulfillV2: + ConnectorIntegrationV2<PoFulfill, PayoutFlowData, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutQuoteV2 +pub trait PayoutQuoteV2: + ConnectorIntegrationV2<PoQuote, PayoutFlowData, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutRecipientV2 +pub trait PayoutRecipientV2: + ConnectorIntegrationV2<PoRecipient, PayoutFlowData, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutRecipientAccountV2 +pub trait PayoutRecipientAccountV2: + ConnectorIntegrationV2<PoRecipientAccount, PayoutFlowData, PayoutsData, PayoutsResponseData> +{ +} + +/// trait PayoutSyncV2 +pub trait PayoutSyncV2: + ConnectorIntegrationV2<PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData> +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/refunds.rs b/crates/hyperswitch_interfaces/src/api/refunds.rs new file mode 100644 index 00000000000..f09c0d1aead --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/refunds.rs @@ -0,0 +1,21 @@ +//! Refunds interface + +use hyperswitch_domain_models::{ + router_flow_types::{Execute, RSync}, + router_request_types::RefundsData, + router_response_types::RefundsResponseData, +}; + +use crate::api::{self, ConnectorCommon}; + +/// trait RefundExecute +pub trait RefundExecute: + api::ConnectorIntegration<Execute, RefundsData, RefundsResponseData> +{ +} + +/// trait RefundSync +pub trait RefundSync: api::ConnectorIntegration<RSync, RefundsData, RefundsResponseData> {} + +/// trait Refund +pub trait Refund: ConnectorCommon + RefundExecute + RefundSync {} diff --git a/crates/hyperswitch_interfaces/src/api/refunds_v2.rs b/crates/hyperswitch_interfaces/src/api/refunds_v2.rs new file mode 100644 index 00000000000..7812c3e2831 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api/refunds_v2.rs @@ -0,0 +1,25 @@ +//! Refunds V2 interface + +use hyperswitch_domain_models::{ + router_data_v2::flow_common_types::RefundFlowData, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::RefundsData, + router_response_types::RefundsResponseData, +}; + +use crate::api::{ConnectorCommon, ConnectorIntegrationV2}; + +/// trait RefundExecuteV2 +pub trait RefundExecuteV2: + ConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData> +{ +} + +/// trait RefundSyncV2 +pub trait RefundSyncV2: + ConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData> +{ +} + +/// trait RefundV2 +pub trait RefundV2: ConnectorCommon + RefundExecuteV2 + RefundSyncV2 {} diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index 2f0c5c2fbda..06a1d6028e6 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -1,5 +1,45 @@ //! Types interface +use hyperswitch_domain_models::{ + router_data::AccessToken, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + dispute::{Accept, Defend, Evidence}, + files::{Retrieve, Upload}, + mandate_revoke::MandateRevoke, + payments::{ + Authorize, AuthorizeSessionToken, Balance, Capture, CompleteAuthorize, + CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, + PaymentMethodToken, PostProcessing, PreProcessing, Session, SetupMandate, Void, + }, + refunds::{Execute, RSync}, + webhooks::VerifyWebhookSource, + }, + router_request_types::{ + AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, + CompleteAuthorizeData, ConnectorCustomerData, DefendDisputeRequestData, + MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsSessionData, + PaymentsSyncData, RefundsData, RetrieveFileRequestData, SetupMandateRequestData, + SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData, + }, + router_response_types::{ + AcceptDisputeResponse, DefendDisputeResponse, MandateRevokeResponseData, + PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, + UploadFileResponse, VerifyWebhookSourceResponseData, + }, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, + PoSync, + }, + router_request_types::PayoutsData, + router_response_types::PayoutsResponseData, +}; +use crate::api::ConnectorIntegration; /// struct Response #[derive(Clone, Debug)] pub struct Response { @@ -10,3 +50,124 @@ pub struct Response { /// status code pub status_code: u16, } + +/// Type alias for `ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>` +pub type PaymentsAuthorizeType = + dyn ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>` +pub type SetupMandateType = + dyn ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>` +pub type MandateRevokeType = + dyn ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; +/// Type alias for `ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>` +pub type PaymentsPreProcessingType = + dyn ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>` +pub type PaymentsPostProcessingType = + dyn ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>` +pub type PaymentsCompleteAuthorizeType = + dyn ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>` +pub type PaymentsPreAuthorizeType = dyn ConnectorIntegration< + AuthorizeSessionToken, + AuthorizeSessionTokenData, + PaymentsResponseData, +>; +/// Type alias for `ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>` +pub type PaymentsInitType = + dyn ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<Balance, PaymentsAuthorizeData, PaymentsResponseData` +pub type PaymentsBalanceType = + dyn ConnectorIntegration<Balance, PaymentsAuthorizeData, PaymentsResponseData>; +/// Type alias for `PaymentsSyncType = dyn ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>` +pub type PaymentsSyncType = dyn ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>` +pub type PaymentsCaptureType = + dyn ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>` +pub type PaymentsSessionType = + dyn ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>` +pub type PaymentsVoidType = + dyn ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>; + +/// Type alias for `ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>` +pub type TokenizationType = dyn ConnectorIntegration< + PaymentMethodToken, + PaymentMethodTokenizationData, + PaymentsResponseData, +>; +/// Type alias for `ConnectorIntegration<IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData>` +pub type IncrementalAuthorizationType = dyn ConnectorIntegration< + IncrementalAuthorization, + PaymentsIncrementalAuthorizationData, + PaymentsResponseData, +>; + +/// Type alias for `ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>` +pub type ConnectorCustomerType = + dyn ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; + +/// Type alias for `ConnectorIntegration<Execute, RefundsData, RefundsResponseData>` +pub type RefundExecuteType = dyn ConnectorIntegration<Execute, RefundsData, RefundsResponseData>; +/// Type alias for `ConnectorIntegration<RSync, RefundsData, RefundsResponseData>` +pub type RefundSyncType = dyn ConnectorIntegration<RSync, RefundsData, RefundsResponseData>; + +/// Type alias for `ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData>` +#[cfg(feature = "payouts")] +pub type PayoutCancelType = dyn ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData>` +#[cfg(feature = "payouts")] +pub type PayoutCreateType = dyn ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>` +#[cfg(feature = "payouts")] +pub type PayoutEligibilityType = + dyn ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData>` +#[cfg(feature = "payouts")] +pub type PayoutFulfillType = dyn ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>` +#[cfg(feature = "payouts")] +pub type PayoutRecipientType = + dyn ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>` +#[cfg(feature = "payouts")] +pub type PayoutRecipientAccountType = + dyn ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData>` +#[cfg(feature = "payouts")] +pub type PayoutQuoteType = dyn ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>` +#[cfg(feature = "payouts")] +pub type PayoutSyncType = dyn ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>` +pub type RefreshTokenType = + dyn ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>; + +/// Type alias for `ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>` +pub type AcceptDisputeType = + dyn ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; +/// Type alias for `ConnectorIntegration<VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData>` +pub type VerifyWebhookSourceType = dyn ConnectorIntegration< + VerifyWebhookSource, + VerifyWebhookSourceRequestData, + VerifyWebhookSourceResponseData, +>; + +/// Type alias for `ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>` +pub type SubmitEvidenceType = + dyn ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; + +/// Type alias for `ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>` +pub type UploadFileType = + dyn ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>; + +/// Type alias for `ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>` +pub type RetrieveFileType = + dyn ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; + +/// Type alias for `ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>` +pub type DefendDisputeType = + dyn ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>; diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 62ddb0067b6..dc54ee37a41 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -16,17 +16,17 @@ keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"] encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"] email = ["external_services/email", "scheduler/email", "olap"] keymanager_create = [] -frm = ["api_models/frm", "hyperswitch_domain_models/frm"] +frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"] stripe = ["dep:serde_qs"] release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] accounts_cache = [] vergen = ["router_env/vergen"] -dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "kgraph_utils/dummy_connector"] +dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector","hyperswitch_interfaces/dummy_connector", "kgraph_utils/dummy_connector"] external_access_dc = ["dummy_connector"] detailed_errors = ["api_models/detailed_errors", "error-stack/serde"] -payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts"] +payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts"] payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] @@ -126,9 +126,10 @@ diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_ euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } events = { version = "0.1.0", path = "../events" } external_services = { version = "0.1.0", path = "../external_services" } +hyperswitch_connectors = { version = "0.1.0", path = "../hyperswitch_connectors" , default-features = false } hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } -hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false } kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" } masking = { version = "0.1.0", path = "../masking" } pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 3a938d0ba60..365b0ca87a6 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -27,7 +27,6 @@ pub mod globalpay; pub mod globepay; pub mod gocardless; pub mod gpayments; -pub mod helcim; pub mod iatapay; pub mod itaubank; pub mod klarna; @@ -70,6 +69,8 @@ pub mod worldpay; pub mod zen; pub mod zsl; +pub use hyperswitch_connectors::connectors::{helcim, helcim::Helcim}; + #[cfg(feature = "dummy_connector")] pub use self::dummyconnector::DummyConnector; pub use self::{ @@ -79,8 +80,8 @@ pub use self::{ boku::Boku, braintree::Braintree, cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay, cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, fiserv::Fiserv, forte::Forte, globalpay::Globalpay, - globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments, helcim::Helcim, - iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, + globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, + itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 96d17edc0e1..90d11ba7b8b 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -282,9 +282,12 @@ impl ConnectorValidation for Adyen { fn validate_psync_reference_id( &self, - data: &types::PaymentsSyncRouterData, + data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { - if data.request.encoded_data.is_some() { + if data.encoded_data.is_some() { return Ok(()); } Err(errors::ConnectorError::MissingRequiredField { diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index 7fb4869dc83..f5ed5189315 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -196,10 +196,13 @@ impl ConnectorValidation for Bluesnap { fn validate_psync_reference_id( &self, - data: &types::PaymentsSyncRouterData, + data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + is_three_ds: bool, + status: enums::AttemptStatus, + connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // If 3DS payment was triggered, connector will have context about payment in CompleteAuthorizeFlow and thus can't make force_sync - if data.is_three_ds() && data.status == enums::AttemptStatus::AuthenticationPending { + if is_three_ds && status == enums::AttemptStatus::AuthenticationPending { return Err( errors::ConnectorError::MissingConnectorRelatedTransactionID { id: "connector_transaction_id".to_string(), @@ -209,7 +212,6 @@ impl ConnectorValidation for Bluesnap { } // if connector_transaction_id is present, psync can be made if data - .request .connector_transaction_id .get_connector_transaction_id() .is_ok() @@ -218,7 +220,7 @@ impl ConnectorValidation for Bluesnap { } // if merchant_id is present, psync can be made along with attempt_id let meta_data: CustomResult<bluesnap::BluesnapConnectorMetaData, errors::ConnectorError> = - connector_utils::to_connector_meta_from_secret(data.connector_meta_data.clone()); + connector_utils::to_connector_meta_from_secret(connector_meta_data.clone()); meta_data.map(|_| ()) } diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs index 40f85843755..fccc8784dcd 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/router/src/connector/cryptopay.rs @@ -327,7 +327,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P impl ConnectorValidation for Cryptopay { fn validate_psync_reference_id( &self, - _data: &types::PaymentsSyncRouterData, + _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _is_three_ds: bool, + _status: common_enums::enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria Ok(()) diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs index 2c0712c5408..19f2eb8ade3 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/router/src/connector/nmi.rs @@ -124,7 +124,10 @@ impl ConnectorValidation for Nmi { fn validate_psync_reference_id( &self, - _data: &types::PaymentsSyncRouterData, + _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // in case we dont have transaction id, we can make psync using attempt id Ok(()) diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index d9e476ac1f9..e30097bd539 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -205,7 +205,10 @@ impl ConnectorValidation for Noon { fn validate_psync_reference_id( &self, - _data: &types::PaymentsSyncRouterData, + _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria Ok(()) diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs index e76216f4dcd..666beca5ba4 100644 --- a/crates/router/src/connector/zen.rs +++ b/crates/router/src/connector/zen.rs @@ -139,7 +139,10 @@ impl ConnectorCommon for Zen { impl ConnectorValidation for Zen { fn validate_psync_reference_id( &self, - _data: &types::PaymentsSyncRouterData, + _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _is_three_ds: bool, + _status: common_enums::enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria Ok(()) diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs index e86f94dc251..dbb50b18032 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -661,7 +661,6 @@ default_imp_for_new_connector_integration_payment!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -748,7 +747,6 @@ default_imp_for_new_connector_integration_refund!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -830,7 +828,6 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -934,7 +931,6 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1020,7 +1016,6 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1090,7 +1085,6 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1187,7 +1181,6 @@ default_imp_for_new_connector_integration_file_upload!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1355,7 +1348,6 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1444,7 +1436,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1533,7 +1524,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1622,7 +1612,6 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1711,7 +1700,6 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1800,7 +1788,6 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1889,7 +1876,6 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1978,7 +1964,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2065,7 +2050,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2233,7 +2217,6 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2322,7 +2305,6 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2411,7 +2393,6 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2500,7 +2481,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2589,7 +2569,6 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2675,7 +2654,6 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 3e9d18d117f..32d739bcf9f 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -206,7 +206,6 @@ default_imp_for_complete_authorize!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -294,7 +293,6 @@ default_imp_for_webhook_source_verification!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -390,7 +388,6 @@ default_imp_for_create_customer!( connector::Globalpay, connector::Globepay, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -652,7 +649,6 @@ default_imp_for_accept_dispute!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -771,7 +767,6 @@ default_imp_for_file_upload!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -867,7 +862,6 @@ default_imp_for_submit_evidence!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -963,7 +957,6 @@ default_imp_for_defend_dispute!( connector::Globalpay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1074,7 +1067,6 @@ default_imp_for_pre_processing_steps!( connector::Globalpay, connector::Globepay, connector::Gpayments, - connector::Helcim, connector::Klarna, connector::Mifinity, connector::Mollie, @@ -1157,7 +1149,6 @@ default_imp_for_post_processing_steps!( connector::Globalpay, connector::Globepay, connector::Gpayments, - connector::Helcim, connector::Klarna, connector::Mifinity, connector::Mollie, @@ -1318,7 +1309,6 @@ default_imp_for_payouts_create!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1414,7 +1404,6 @@ default_imp_for_payouts_retrieve!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1513,7 +1502,6 @@ default_imp_for_payouts_eligibility!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1607,7 +1595,6 @@ default_imp_for_payouts_fulfill!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1700,7 +1687,6 @@ default_imp_for_payouts_cancel!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1796,7 +1782,6 @@ default_imp_for_payouts_quote!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1893,7 +1878,6 @@ default_imp_for_payouts_recipient!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -1993,7 +1977,6 @@ default_imp_for_payouts_recipient_account!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2090,7 +2073,6 @@ default_imp_for_approve!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2188,7 +2170,6 @@ default_imp_for_reject!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2368,7 +2349,6 @@ default_imp_for_frm_sale!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2466,7 +2446,6 @@ default_imp_for_frm_checkout!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2564,7 +2543,6 @@ default_imp_for_frm_transaction!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2662,7 +2640,6 @@ default_imp_for_frm_fulfillment!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2760,7 +2737,6 @@ default_imp_for_frm_record_return!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2855,7 +2831,6 @@ default_imp_for_incremental_authorization!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -2950,7 +2925,6 @@ default_imp_for_revoking_mandates!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, @@ -3198,7 +3172,6 @@ default_imp_for_authorize_session_token!( connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, connector::Klarna, diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index cb6c6f50d5e..ab53aee86d1 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -4,6 +4,7 @@ use async_trait::async_trait; use super::{ConstructFlowSpecificData, Feature}; use crate::{ + connector::utils::RouterData, core::{ errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, @@ -12,7 +13,6 @@ use crate::{ services::{self, api::ConnectorValidation, logger}, types::{self, api, domain, storage}, }; - #[async_trait] impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for PaymentData<api::PSync> @@ -151,7 +151,12 @@ impl Feature<api::PSync, types::PaymentsSyncData> //validate_psync_reference_id if call_connector_action is trigger if connector .connector - .validate_psync_reference_id(self) + .validate_psync_reference_id( + &self.request, + self.is_three_ds(), + self.status, + self.connector_meta_data.clone(), + ) .is_err() { logger::warn!( diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index ea9ce177439..e9caddcb35d 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -17,7 +17,6 @@ use actix_web::{ http::header::{HeaderName, HeaderValue}, web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError, }; -use api_models::enums::{CaptureMethod, PaymentMethodType}; pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient}; pub use common_utils::request::{ContentType, Method, Request, RequestBuilder}; use common_utils::{ @@ -37,7 +36,8 @@ pub use hyperswitch_domain_models::{ }; pub use hyperswitch_interfaces::{ api::{ - BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration, ConnectorIntegrationAny, + BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration, + ConnectorIntegrationAny, ConnectorValidation, }, connector_integration_v2::{ BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2, @@ -75,11 +75,7 @@ use crate::{ connector_integration_interface::RouterDataConversion, generic_link_response::build_generic_link_html, }, - types::{ - self, - api::{self, ConnectorCommon}, - ErrorResponse, - }, + types::{self, api, ErrorResponse}, }; pub type BoxedPaymentConnectorIntegrationInterface<T, Req, Resp> = @@ -105,61 +101,6 @@ pub type BoxedAccessTokenConnectorIntegrationInterface<T, Req, Resp> = pub type BoxedFilesConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::FilesFlowData, Req, Resp>; -pub trait ConnectorValidation: ConnectorCommon { - fn validate_capture_method( - &self, - capture_method: Option<CaptureMethod>, - _pmt: Option<PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - CaptureMethod::Automatic => Ok(()), - CaptureMethod::Manual | CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => { - Err(errors::ConnectorError::NotSupported { - message: capture_method.to_string(), - connector: self.id(), - } - .into()) - } - } - } - - fn validate_mandate_payment( - &self, - pm_type: Option<PaymentMethodType>, - _pm_data: types::domain::payments::PaymentMethodData, - ) -> CustomResult<(), errors::ConnectorError> { - let connector = self.id(); - match pm_type { - Some(pm_type) => Err(errors::ConnectorError::NotSupported { - message: format!("{} mandate payment", pm_type), - connector, - } - .into()), - None => Err(errors::ConnectorError::NotSupported { - message: " mandate payment".to_string(), - connector, - } - .into()), - } - } - - fn validate_psync_reference_id( - &self, - data: &types::PaymentsSyncRouterData, - ) -> CustomResult<(), errors::ConnectorError> { - data.request - .connector_transaction_id - .get_connector_transaction_id() - .change_context(errors::ConnectorError::MissingConnectorTransactionID) - .map(|_| ()) - } - - fn is_webhook_source_verification_mandatory(&self) -> bool { - false - } -} - /// Handle the flow by interacting with connector module /// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger` /// In other cases, It will be created if required, even if it is not passed diff --git a/crates/router/src/services/connector_integration_interface.rs b/crates/router/src/services/connector_integration_interface.rs index 8af9d0b58c3..0f4eec49eb6 100644 --- a/crates/router/src/services/connector_integration_interface.rs +++ b/crates/router/src/services/connector_integration_interface.rs @@ -359,11 +359,24 @@ impl ConnectorValidation for ConnectorEnum { fn validate_psync_reference_id( &self, - data: &types::PaymentsSyncRouterData, + data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + is_three_ds: bool, + status: common_enums::enums::AttemptStatus, + connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { match self { - Self::Old(connector) => connector.validate_psync_reference_id(data), - Self::New(connector) => connector.validate_psync_reference_id(data), + Self::Old(connector) => connector.validate_psync_reference_id( + data, + is_three_ds, + status, + connector_meta_data, + ), + Self::New(connector) => connector.validate_psync_reference_id( + data, + is_three_ds, + status, + connector_meta_data, + ), } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index c5e536de3aa..0ee8c4f991f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -23,6 +23,20 @@ pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; pub use common_utils::{pii, pii::Email, request::RequestContent, types::MinorUnit}; #[cfg(feature = "frm")] pub use hyperswitch_domain_models::router_data_v2::FrmFlowData; +use hyperswitch_domain_models::router_flow_types::{ + self, + access_token_auth::AccessTokenAuth, + dispute::{Accept, Defend, Evidence}, + files::{Retrieve, Upload}, + mandate_revoke::MandateRevoke, + payments::{ + Approve, Authorize, AuthorizeSessionToken, Balance, Capture, CompleteAuthorize, + CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PostProcessing, + PreProcessing, Reject, Session, SetupMandate, Void, + }, + refunds::{Execute, RSync}, + webhooks::VerifyWebhookSource, +}; pub use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{ @@ -60,7 +74,20 @@ pub use hyperswitch_domain_models::{ router_data_v2::PayoutFlowData, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; -pub use hyperswitch_interfaces::types::Response; +pub use hyperswitch_interfaces::types::{ + AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, IncrementalAuthorizationType, + MandateRevokeType, PaymentsAuthorizeType, PaymentsBalanceType, PaymentsCaptureType, + PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostProcessingType, + PaymentsPreAuthorizeType, PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType, + PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response, + RetrieveFileType, SetupMandateType, SubmitEvidenceType, TokenizationType, UploadFileType, + VerifyWebhookSourceType, +}; +#[cfg(feature = "payouts")] +pub use hyperswitch_interfaces::types::{ + PayoutCancelType, PayoutCreateType, PayoutEligibilityType, PayoutFulfillType, PayoutQuoteType, + PayoutRecipientAccountType, PayoutRecipientType, PayoutSyncType, +}; pub use crate::core::payments::CustomerDetails; #[cfg(feature = "payouts")] @@ -77,232 +104,94 @@ use crate::{ services, types::transformers::{ForeignFrom, ForeignTryFrom}, }; + pub type PaymentsAuthorizeRouterData = - RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>; + RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = - RouterData<api::PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; + RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; pub type PaymentsPostProcessingRouterData = - RouterData<api::PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; + RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = - RouterData<api::AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; + RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = - RouterData<api::CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; + RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsInitRouterData = - RouterData<api::InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; + RouterData<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsBalanceRouterData = - RouterData<api::Balance, PaymentsAuthorizeData, PaymentsResponseData>; -pub type PaymentsSyncRouterData = RouterData<api::PSync, PaymentsSyncData, PaymentsResponseData>; -pub type PaymentsCaptureRouterData = - RouterData<api::Capture, PaymentsCaptureData, PaymentsResponseData>; + RouterData<Balance, PaymentsAuthorizeData, PaymentsResponseData>; +pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; +pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsIncrementalAuthorizationRouterData = RouterData< - api::IncrementalAuthorization, + IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; -pub type PaymentsCancelRouterData = RouterData<api::Void, PaymentsCancelData, PaymentsResponseData>; -pub type PaymentsRejectRouterData = - RouterData<api::Reject, PaymentsRejectData, PaymentsResponseData>; -pub type PaymentsApproveRouterData = - RouterData<api::Approve, PaymentsApproveData, PaymentsResponseData>; -pub type PaymentsSessionRouterData = - RouterData<api::Session, PaymentsSessionData, PaymentsResponseData>; +pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; +pub type PaymentsRejectRouterData = RouterData<Reject, PaymentsRejectData, PaymentsResponseData>; +pub type PaymentsApproveRouterData = RouterData<Approve, PaymentsApproveData, PaymentsResponseData>; +pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; -pub type RefundExecuteRouterData = RouterData<api::Execute, RefundsData, RefundsResponseData>; -pub type RefundSyncRouterData = RouterData<api::RSync, RefundsData, RefundsResponseData>; -pub type TokenizationRouterData = - RouterData<api::PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>; +pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>; +pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; +pub type TokenizationRouterData = RouterData< + router_flow_types::PaymentMethodToken, + PaymentMethodTokenizationData, + PaymentsResponseData, +>; pub type ConnectorCustomerRouterData = - RouterData<api::CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; + RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; -pub type RefreshTokenRouterData = - RouterData<api::AccessTokenAuth, AccessTokenRequestData, AccessToken>; +pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsResponseRouterData<R> = - ResponseRouterData<api::Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; + ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCancelResponseRouterData<R> = - ResponseRouterData<api::Void, R, PaymentsCancelData, PaymentsResponseData>; + ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsBalanceResponseRouterData<R> = - ResponseRouterData<api::Balance, R, PaymentsAuthorizeData, PaymentsResponseData>; + ResponseRouterData<Balance, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncResponseRouterData<R> = - ResponseRouterData<api::PSync, R, PaymentsSyncData, PaymentsResponseData>; + ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsSessionResponseRouterData<R> = - ResponseRouterData<api::Session, R, PaymentsSessionData, PaymentsResponseData>; + ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsInitResponseRouterData<R> = - ResponseRouterData<api::InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; + ResponseRouterData<InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCaptureResponseRouterData<R> = - ResponseRouterData<api::Capture, R, PaymentsCaptureData, PaymentsResponseData>; + ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsPreprocessingResponseRouterData<R> = - ResponseRouterData<api::PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>; -pub type TokenizationResponseRouterData<R> = ResponseRouterData< - api::PaymentMethodToken, - R, - PaymentMethodTokenizationData, - PaymentsResponseData, ->; -pub type ConnectorCustomerResponseRouterData<R> = ResponseRouterData< - api::CreateConnectorCustomer, - R, - ConnectorCustomerData, - PaymentsResponseData, ->; + ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>; +pub type TokenizationResponseRouterData<R> = + ResponseRouterData<PaymentMethodToken, R, PaymentMethodTokenizationData, PaymentsResponseData>; +pub type ConnectorCustomerResponseRouterData<R> = + ResponseRouterData<CreateConnectorCustomer, R, ConnectorCustomerData, PaymentsResponseData>; pub type RefundsResponseRouterData<F, R> = ResponseRouterData<F, R, RefundsData, RefundsResponseData>; -pub type PaymentsAuthorizeType = - dyn services::ConnectorIntegration<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>; -pub type SetupMandateType = dyn services::ConnectorIntegration< - api::SetupMandate, - SetupMandateRequestData, - PaymentsResponseData, ->; -pub type MandateRevokeType = dyn services::ConnectorIntegration< - api::MandateRevoke, - MandateRevokeRequestData, - MandateRevokeResponseData, ->; -pub type PaymentsPreProcessingType = dyn services::ConnectorIntegration< - api::PreProcessing, - PaymentsPreProcessingData, - PaymentsResponseData, ->; -pub type PaymentsPostProcessingType = dyn services::ConnectorIntegration< - api::PostProcessing, - PaymentsPostProcessingData, - PaymentsResponseData, ->; -pub type PaymentsCompleteAuthorizeType = dyn services::ConnectorIntegration< - api::CompleteAuthorize, - CompleteAuthorizeData, - PaymentsResponseData, ->; -pub type PaymentsPreAuthorizeType = dyn services::ConnectorIntegration< - api::AuthorizeSessionToken, - AuthorizeSessionTokenData, - PaymentsResponseData, ->; -pub type PaymentsInitType = dyn services::ConnectorIntegration< - api::InitPayment, - PaymentsAuthorizeData, - PaymentsResponseData, ->; -pub type PaymentsBalanceType = - dyn services::ConnectorIntegration<api::Balance, PaymentsAuthorizeData, PaymentsResponseData>; -pub type PaymentsSyncType = - dyn services::ConnectorIntegration<api::PSync, PaymentsSyncData, PaymentsResponseData>; -pub type PaymentsCaptureType = - dyn services::ConnectorIntegration<api::Capture, PaymentsCaptureData, PaymentsResponseData>; -pub type PaymentsSessionType = - dyn services::ConnectorIntegration<api::Session, PaymentsSessionData, PaymentsResponseData>; -pub type PaymentsVoidType = - dyn services::ConnectorIntegration<api::Void, PaymentsCancelData, PaymentsResponseData>; -pub type TokenizationType = dyn services::ConnectorIntegration< - api::PaymentMethodToken, - PaymentMethodTokenizationData, - PaymentsResponseData, ->; -pub type IncrementalAuthorizationType = dyn services::ConnectorIntegration< - api::IncrementalAuthorization, - PaymentsIncrementalAuthorizationData, - PaymentsResponseData, ->; - -pub type ConnectorCustomerType = dyn services::ConnectorIntegration< - api::CreateConnectorCustomer, - ConnectorCustomerData, - PaymentsResponseData, ->; - -pub type RefundExecuteType = - dyn services::ConnectorIntegration<api::Execute, RefundsData, RefundsResponseData>; -pub type RefundSyncType = - dyn services::ConnectorIntegration<api::RSync, RefundsData, RefundsResponseData>; - -#[cfg(feature = "payouts")] -pub type PayoutCancelType = - dyn services::ConnectorIntegration<api::PoCancel, PayoutsData, PayoutsResponseData>; -#[cfg(feature = "payouts")] -pub type PayoutCreateType = - dyn services::ConnectorIntegration<api::PoCreate, PayoutsData, PayoutsResponseData>; -#[cfg(feature = "payouts")] -pub type PayoutEligibilityType = - dyn services::ConnectorIntegration<api::PoEligibility, PayoutsData, PayoutsResponseData>; -#[cfg(feature = "payouts")] -pub type PayoutFulfillType = - dyn services::ConnectorIntegration<api::PoFulfill, PayoutsData, PayoutsResponseData>; -#[cfg(feature = "payouts")] -pub type PayoutRecipientType = - dyn services::ConnectorIntegration<api::PoRecipient, PayoutsData, PayoutsResponseData>; -#[cfg(feature = "payouts")] -pub type PayoutRecipientAccountType = - dyn services::ConnectorIntegration<api::PoRecipientAccount, PayoutsData, PayoutsResponseData>; -#[cfg(feature = "payouts")] -pub type PayoutQuoteType = - dyn services::ConnectorIntegration<api::PoQuote, PayoutsData, PayoutsResponseData>; -#[cfg(feature = "payouts")] -pub type PayoutSyncType = - dyn services::ConnectorIntegration<api::PoSync, PayoutsData, PayoutsResponseData>; - -pub type RefreshTokenType = - dyn services::ConnectorIntegration<api::AccessTokenAuth, AccessTokenRequestData, AccessToken>; - -pub type AcceptDisputeType = dyn services::ConnectorIntegration< - api::Accept, - AcceptDisputeRequestData, - AcceptDisputeResponse, ->; -pub type VerifyWebhookSourceType = dyn services::ConnectorIntegration< - api::VerifyWebhookSource, - VerifyWebhookSourceRequestData, - VerifyWebhookSourceResponseData, ->; - -pub type SubmitEvidenceType = dyn services::ConnectorIntegration< - api::Evidence, - SubmitEvidenceRequestData, - SubmitEvidenceResponse, ->; - -pub type UploadFileType = - dyn services::ConnectorIntegration<api::Upload, UploadFileRequestData, UploadFileResponse>; - -pub type RetrieveFileType = dyn services::ConnectorIntegration< - api::Retrieve, - RetrieveFileRequestData, - RetrieveFileResponse, ->; - -pub type DefendDisputeType = dyn services::ConnectorIntegration< - api::Defend, - DefendDisputeRequestData, - DefendDisputeResponse, ->; - pub type SetupMandateRouterData = - RouterData<api::SetupMandate, SetupMandateRequestData, PaymentsResponseData>; + RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type AcceptDisputeRouterData = - RouterData<api::Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; + RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; pub type VerifyWebhookSourceRouterData = RouterData< - api::VerifyWebhookSource, + VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; pub type SubmitEvidenceRouterData = - RouterData<api::Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; + RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; -pub type UploadFileRouterData = RouterData<api::Upload, UploadFileRequestData, UploadFileResponse>; +pub type UploadFileRouterData = RouterData<Upload, UploadFileRequestData, UploadFileResponse>; pub type RetrieveFileRouterData = - RouterData<api::Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; + RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; pub type DefendDisputeRouterData = - RouterData<api::Defend, DefendDisputeRequestData, DefendDisputeResponse>; + RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>; pub type MandateRevokeRouterData = - RouterData<api::MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; + RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index b2858b23d5b..e08248676d2 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -39,11 +39,15 @@ pub mod refunds_v2; use std::{fmt::Debug, str::FromStr}; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::router_data_v2::AccessTokenFlowData; pub use hyperswitch_domain_models::router_flow_types::{ - access_token_auth::AccessTokenAuth, webhooks::VerifyWebhookSource, + access_token_auth::AccessTokenAuth, mandate_revoke::MandateRevoke, + webhooks::VerifyWebhookSource, +}; +pub use hyperswitch_interfaces::api::{ + ConnectorAccessToken, ConnectorAccessTokenV2, ConnectorCommon, ConnectorCommonExt, + ConnectorMandateRevoke, ConnectorMandateRevokeV2, ConnectorVerifyWebhookSource, + ConnectorVerifyWebhookSourceV2, CurrencyUnit, }; -pub use hyperswitch_interfaces::api::{ConnectorCommon, ConnectorCommonExt, CurrencyUnit}; #[cfg(feature = "frm")] pub use self::fraud_check::*; @@ -51,7 +55,8 @@ pub use self::fraud_check::*; pub use self::payouts::*; pub use self::{ admin::*, api_keys::*, authentication::*, configs::*, customers::*, disputes::*, files::*, - payment_link::*, payment_methods::*, payments::*, poll::*, refunds::*, webhooks::*, + payment_link::*, payment_methods::*, payments::*, poll::*, refunds::*, refunds_v2::*, + webhooks::*, }; use crate::{ configs::settings::Connectors, @@ -60,26 +65,9 @@ use crate::{ errors::{self, CustomResult}, payments::types as payments_types, }, - services::{ - connector_integration_interface::ConnectorEnum, ConnectorIntegration, - ConnectorIntegrationV2, ConnectorRedirectResponse, ConnectorValidation, - }, + services::{connector_integration_interface::ConnectorEnum, ConnectorRedirectResponse}, types::{self, api::enums as api_enums}, }; -pub trait ConnectorAccessToken: - ConnectorIntegration<AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> -{ -} - -pub trait ConnectorAccessTokenV2: - ConnectorIntegrationV2< - AccessTokenAuth, - AccessTokenFlowData, - types::AccessTokenRequestData, - types::AccessToken, -> -{ -} #[derive(Clone)] pub enum ConnectorCallType { @@ -88,46 +76,6 @@ pub enum ConnectorCallType { SessionMultiple(Vec<SessionConnectorData>), } -pub trait ConnectorVerifyWebhookSource: - ConnectorIntegration< - VerifyWebhookSource, - types::VerifyWebhookSourceRequestData, - types::VerifyWebhookSourceResponseData, -> -{ -} -pub trait ConnectorVerifyWebhookSourceV2: - ConnectorIntegrationV2< - VerifyWebhookSource, - types::WebhookSourceVerifyData, - types::VerifyWebhookSourceRequestData, - types::VerifyWebhookSourceResponseData, -> -{ -} - -#[derive(Clone, Debug)] -pub struct MandateRevoke; - -pub trait ConnectorMandateRevoke: - ConnectorIntegration< - MandateRevoke, - types::MandateRevokeRequestData, - types::MandateRevokeResponseData, -> -{ -} - -pub trait ConnectorMandateRevokeV2: - ConnectorIntegrationV2< - MandateRevoke, - types::MandateRevokeFlowData, - types::MandateRevokeRequestData, - types::MandateRevokeResponseData, -> -{ -} - pub trait ConnectorTransactionId: ConnectorCommon + Sync { fn connector_transaction_id( &self, diff --git a/crates/router/src/types/api/disputes.rs b/crates/router/src/types/api/disputes.rs index 247b8bf45e3..b3bc66e010a 100644 --- a/crates/router/src/types/api/disputes.rs +++ b/crates/router/src/types/api/disputes.rs @@ -1,7 +1,10 @@ -pub use hyperswitch_interfaces::disputes::DisputePayload; +pub use hyperswitch_interfaces::{ + api::disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence}, + disputes::DisputePayload, +}; use masking::{Deserialize, Serialize}; -use crate::{services, types}; +use crate::types; #[derive(Default, Debug, Deserialize, Serialize)] pub struct DisputeId { @@ -47,32 +50,3 @@ pub enum EvidenceType { RecurringTransactionAgreement, UncategorizedFile, } - -pub trait AcceptDispute: - services::ConnectorIntegration< - Accept, - types::AcceptDisputeRequestData, - types::AcceptDisputeResponse, -> -{ -} - -pub trait SubmitEvidence: - services::ConnectorIntegration< - Evidence, - types::SubmitEvidenceRequestData, - types::SubmitEvidenceResponse, -> -{ -} - -pub trait DefendDispute: - services::ConnectorIntegration< - Defend, - types::DefendDisputeRequestData, - types::DefendDisputeResponse, -> -{ -} - -pub trait Dispute: super::ConnectorCommon + AcceptDispute + SubmitEvidence + DefendDispute {} diff --git a/crates/router/src/types/api/disputes_v2.rs b/crates/router/src/types/api/disputes_v2.rs index e9df4cc3cdd..af9594cf60c 100644 --- a/crates/router/src/types/api/disputes_v2.rs +++ b/crates/router/src/types/api/disputes_v2.rs @@ -1,41 +1,3 @@ -use hyperswitch_domain_models::{ - router_data_v2::DisputesFlowData, - router_flow_types::dispute::{Accept, Defend, Evidence}, +pub use hyperswitch_interfaces::api::disputes_v2::{ + AcceptDisputeV2, DefendDisputeV2, DisputeV2, SubmitEvidenceV2, }; - -use crate::{services, types}; - -pub trait AcceptDisputeV2: - services::ConnectorIntegrationV2< - Accept, - DisputesFlowData, - types::AcceptDisputeRequestData, - types::AcceptDisputeResponse, -> -{ -} - -pub trait SubmitEvidenceV2: - services::ConnectorIntegrationV2< - Evidence, - DisputesFlowData, - types::SubmitEvidenceRequestData, - types::SubmitEvidenceResponse, -> -{ -} - -pub trait DefendDisputeV2: - services::ConnectorIntegrationV2< - Defend, - DisputesFlowData, - types::DefendDisputeRequestData, - types::DefendDisputeResponse, -> -{ -} - -pub trait DisputeV2: - super::ConnectorCommon + AcceptDisputeV2 + SubmitEvidenceV2 + DefendDisputeV2 -{ -} diff --git a/crates/router/src/types/api/files.rs b/crates/router/src/types/api/files.rs index fd094014110..9a991c040f4 100644 --- a/crates/router/src/types/api/files.rs +++ b/crates/router/src/types/api/files.rs @@ -1,13 +1,12 @@ use api_models::enums::FileUploadProvider; pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload}; +pub use hyperswitch_interfaces::api::files::{FilePurpose, FileUpload, RetrieveFile, UploadFile}; use masking::{Deserialize, Serialize}; use serde_with::serde_as; pub use super::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2}; -use super::ConnectorCommon; use crate::{ core::errors, - services, types::{self, transformers::ForeignTryFrom}, }; @@ -61,38 +60,3 @@ pub struct CreateFileRequest { pub purpose: FilePurpose, pub dispute_id: Option<String>, } - -#[derive(Debug, serde::Deserialize, strum::Display, Clone, serde::Serialize)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum FilePurpose { - DisputeEvidence, -} - -pub trait UploadFile: - services::ConnectorIntegration<Upload, types::UploadFileRequestData, types::UploadFileResponse> -{ -} - -pub trait RetrieveFile: - services::ConnectorIntegration< - Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, -> -{ -} - -pub trait FileUpload: ConnectorCommon + Sync + UploadFile + RetrieveFile { - fn validate_file_upload( - &self, - _purpose: FilePurpose, - _file_size: i32, - _file_type: mime::Mime, - ) -> common_utils::errors::CustomResult<(), errors::ConnectorError> { - Err(errors::ConnectorError::FileValidationFailed { - reason: "".to_owned(), - } - .into()) - } -} diff --git a/crates/router/src/types/api/files_v2.rs b/crates/router/src/types/api/files_v2.rs index 9e9ba423e69..8ea5661ae9a 100644 --- a/crates/router/src/types/api/files_v2.rs +++ b/crates/router/src/types/api/files_v2.rs @@ -1,38 +1,2 @@ pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload}; - -use super::ConnectorCommon; -use crate::{core::errors, services, types, types::api::FilePurpose}; - -pub trait UploadFileV2: - services::ConnectorIntegrationV2< - Upload, - types::FilesFlowData, - types::UploadFileRequestData, - types::UploadFileResponse, -> -{ -} - -pub trait RetrieveFileV2: - services::ConnectorIntegrationV2< - Retrieve, - types::FilesFlowData, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, -> -{ -} - -pub trait FileUploadV2: ConnectorCommon + Sync + UploadFileV2 + RetrieveFileV2 { - fn validate_file_upload_v2( - &self, - _purpose: FilePurpose, - _file_size: i32, - _file_type: mime::Mime, - ) -> common_utils::errors::CustomResult<(), errors::ConnectorError> { - Err(errors::ConnectorError::FileValidationFailed { - reason: "".to_owned(), - } - .into()) - } -} +pub use hyperswitch_interfaces::api::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2}; diff --git a/crates/router/src/types/api/fraud_check.rs b/crates/router/src/types/api/fraud_check.rs index f0d2d0c6f05..2d1a42092f4 100644 --- a/crates/router/src/types/api/fraud_check.rs +++ b/crates/router/src/types/api/fraud_check.rs @@ -6,46 +6,17 @@ use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::fraud_check::{ Checkout, Fulfillment, RecordReturn, Sale, Transaction, }; +pub use hyperswitch_interfaces::api::fraud_check::{ + FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, + FraudCheckTransaction, +}; pub use super::fraud_check_v2::{ FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2, FraudCheckTransactionV2, FraudCheckV2, }; use super::{ConnectorData, SessionConnectorData}; -use crate::{ - connector, - core::errors, - services::{api, connector_integration_interface::ConnectorEnum}, - types::fraud_check::{ - FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, - FraudCheckResponseData, FraudCheckSaleData, FraudCheckTransactionData, - }, -}; - -pub trait FraudCheckSale: - api::ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> -{ -} - -pub trait FraudCheckCheckout: - api::ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> -{ -} - -pub trait FraudCheckTransaction: - api::ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> -{ -} - -pub trait FraudCheckFulfillment: - api::ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> -{ -} - -pub trait FraudCheckRecordReturn: - api::ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> -{ -} +use crate::{connector, core::errors, services::connector_integration_interface::ConnectorEnum}; #[derive(Clone)] pub struct FraudCheckConnectorData { diff --git a/crates/router/src/types/api/fraud_check_v2.rs b/crates/router/src/types/api/fraud_check_v2.rs index 53dad6d5686..c6f2b4a8ff0 100644 --- a/crates/router/src/types/api/fraud_check_v2.rs +++ b/crates/router/src/types/api/fraud_check_v2.rs @@ -1,62 +1,12 @@ pub use hyperswitch_domain_models::router_flow_types::fraud_check::{ Checkout, Fulfillment, RecordReturn, Sale, Transaction, }; - -use crate::{ - services::api, - types::{ - self, - fraud_check::{ - FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, - FraudCheckResponseData, FraudCheckSaleData, FraudCheckTransactionData, - }, - }, +pub use hyperswitch_interfaces::api::fraud_check_v2::{ + FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2, + FraudCheckTransactionV2, }; -pub trait FraudCheckSaleV2: - api::ConnectorIntegrationV2<Sale, types::FrmFlowData, FraudCheckSaleData, FraudCheckResponseData> -{ -} - -pub trait FraudCheckCheckoutV2: - api::ConnectorIntegrationV2< - Checkout, - types::FrmFlowData, - FraudCheckCheckoutData, - FraudCheckResponseData, -> -{ -} - -pub trait FraudCheckTransactionV2: - api::ConnectorIntegrationV2< - Transaction, - types::FrmFlowData, - FraudCheckTransactionData, - FraudCheckResponseData, -> -{ -} - -pub trait FraudCheckFulfillmentV2: - api::ConnectorIntegrationV2< - Fulfillment, - types::FrmFlowData, - FraudCheckFulfillmentData, - FraudCheckResponseData, -> -{ -} - -pub trait FraudCheckRecordReturnV2: - api::ConnectorIntegrationV2< - RecordReturn, - types::FrmFlowData, - FraudCheckRecordReturnData, - FraudCheckResponseData, -> -{ -} +use crate::types; #[cfg(feature = "frm")] pub trait FraudCheckV2: diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 3c1d8175e8b..04889e191b1 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -20,6 +20,12 @@ pub use hyperswitch_domain_models::router_flow_types::payments::{ CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentMethodToken, PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, }; +pub use hyperswitch_interfaces::api::payments::{ + ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize, + PaymentAuthorizeSessionToken, PaymentCapture, PaymentIncrementalAuthorization, PaymentReject, + PaymentSession, PaymentSync, PaymentToken, PaymentVoid, PaymentsCompleteAuthorize, + PaymentsPostProcessing, PaymentsPreProcessing, +}; pub use super::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, @@ -27,11 +33,7 @@ pub use super::payments_v2::{ PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, }; -use crate::{ - core::errors, - services::api, - types::{self, api as api_types}, -}; +use crate::core::errors; impl super::Router for PaymentsRequest {} @@ -76,132 +78,6 @@ impl MandateValidationFieldsExt for MandateValidationFields { } } -// Extract only the last 4 digits of card - -pub trait PaymentAuthorize: - api::ConnectorIntegration<Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> -{ -} - -pub trait PaymentAuthorizeSessionToken: - api::ConnectorIntegration< - AuthorizeSessionToken, - types::AuthorizeSessionTokenData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentSync: - api::ConnectorIntegration<PSync, types::PaymentsSyncData, types::PaymentsResponseData> -{ -} - -pub trait PaymentVoid: - api::ConnectorIntegration<Void, types::PaymentsCancelData, types::PaymentsResponseData> -{ -} - -pub trait PaymentApprove: - api::ConnectorIntegration<Approve, types::PaymentsApproveData, types::PaymentsResponseData> -{ -} - -pub trait PaymentReject: - api::ConnectorIntegration<Reject, types::PaymentsRejectData, types::PaymentsResponseData> -{ -} - -pub trait PaymentCapture: - api::ConnectorIntegration<Capture, types::PaymentsCaptureData, types::PaymentsResponseData> -{ -} - -pub trait PaymentSession: - api::ConnectorIntegration<Session, types::PaymentsSessionData, types::PaymentsResponseData> -{ -} - -pub trait MandateSetup: - api::ConnectorIntegration<SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData> -{ -} - -pub trait PaymentIncrementalAuthorization: - api::ConnectorIntegration< - IncrementalAuthorization, - types::PaymentsIncrementalAuthorizationData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentsCompleteAuthorize: - api::ConnectorIntegration< - CompleteAuthorize, - types::CompleteAuthorizeData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentToken: - api::ConnectorIntegration< - PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, -> -{ -} - -pub trait ConnectorCustomer: - api::ConnectorIntegration< - CreateConnectorCustomer, - types::ConnectorCustomerData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentsPreProcessing: - api::ConnectorIntegration< - PreProcessing, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentsPostProcessing: - api::ConnectorIntegration< - PostProcessing, - types::PaymentsPostProcessingData, - types::PaymentsResponseData, -> -{ -} - -pub trait Payment: - api_types::ConnectorCommon - + api_types::ConnectorValidation - + PaymentAuthorize - + PaymentAuthorizeSessionToken - + PaymentsCompleteAuthorize - + PaymentSync - + PaymentCapture - + PaymentVoid - + PaymentApprove - + PaymentReject - + MandateSetup - + PaymentSession - + PaymentToken - + PaymentsPreProcessing - + PaymentsPostProcessing - + ConnectorCustomer - + PaymentIncrementalAuthorization -{ -} - #[cfg(test)] mod payments_test { #![allow(clippy::expect_used, clippy::unwrap_used)] diff --git a/crates/router/src/types/api/payments_v2.rs b/crates/router/src/types/api/payments_v2.rs index 639dc0de5bc..8d8e3498eff 100644 --- a/crates/router/src/types/api/payments_v2.rs +++ b/crates/router/src/types/api/payments_v2.rs @@ -1,184 +1,6 @@ -use hyperswitch_domain_models::{ - router_data_v2::PaymentFlowData, - router_flow_types::payments::{ - Approve, Authorize, AuthorizeSessionToken, Capture, CompleteAuthorize, - CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, - PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, - }, +pub use hyperswitch_interfaces::api::payments_v2::{ + ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, + PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, PaymentRejectV2, + PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, + PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, }; - -use crate::{ - services::api, - types::{self, api as api_types}, -}; - -pub trait PaymentAuthorizeV2: - api::ConnectorIntegrationV2< - Authorize, - PaymentFlowData, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentAuthorizeSessionTokenV2: - api::ConnectorIntegrationV2< - AuthorizeSessionToken, - PaymentFlowData, - types::AuthorizeSessionTokenData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentSyncV2: - api::ConnectorIntegrationV2< - PSync, - PaymentFlowData, - types::PaymentsSyncData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentVoidV2: - api::ConnectorIntegrationV2< - Void, - PaymentFlowData, - types::PaymentsCancelData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentApproveV2: - api::ConnectorIntegrationV2< - Approve, - PaymentFlowData, - types::PaymentsApproveData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentRejectV2: - api::ConnectorIntegrationV2< - Reject, - PaymentFlowData, - types::PaymentsRejectData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentCaptureV2: - api::ConnectorIntegrationV2< - Capture, - PaymentFlowData, - types::PaymentsCaptureData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentSessionV2: - api::ConnectorIntegrationV2< - Session, - PaymentFlowData, - types::PaymentsSessionData, - types::PaymentsResponseData, -> -{ -} - -pub trait MandateSetupV2: - api::ConnectorIntegrationV2< - SetupMandate, - PaymentFlowData, - types::SetupMandateRequestData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentIncrementalAuthorizationV2: - api::ConnectorIntegrationV2< - IncrementalAuthorization, - PaymentFlowData, - types::PaymentsIncrementalAuthorizationData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentsCompleteAuthorizeV2: - api::ConnectorIntegrationV2< - CompleteAuthorize, - PaymentFlowData, - types::CompleteAuthorizeData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentTokenV2: - api::ConnectorIntegrationV2< - PaymentMethodToken, - PaymentFlowData, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, -> -{ -} - -pub trait ConnectorCustomerV2: - api::ConnectorIntegrationV2< - CreateConnectorCustomer, - PaymentFlowData, - types::ConnectorCustomerData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentsPreProcessingV2: - api::ConnectorIntegrationV2< - PreProcessing, - PaymentFlowData, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentsPostProcessingV2: - api::ConnectorIntegrationV2< - PostProcessing, - PaymentFlowData, - types::PaymentsPostProcessingData, - types::PaymentsResponseData, -> -{ -} - -pub trait PaymentV2: - api_types::ConnectorCommon - + api_types::ConnectorValidation - + PaymentAuthorizeV2 - + PaymentAuthorizeSessionTokenV2 - + PaymentsCompleteAuthorizeV2 - + PaymentSyncV2 - + PaymentCaptureV2 - + PaymentVoidV2 - + PaymentApproveV2 - + PaymentRejectV2 - + MandateSetupV2 - + PaymentSessionV2 - + PaymentTokenV2 - + PaymentsPreProcessingV2 - + PaymentsPostProcessingV2 - + ConnectorCustomerV2 - + PaymentIncrementalAuthorizationV2 -{ -} diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs index 777b1e68b5c..0e89950d69e 100644 --- a/crates/router/src/types/api/payouts.rs +++ b/crates/router/src/types/api/payouts.rs @@ -7,49 +7,12 @@ pub use api_models::payouts::{ pub use hyperswitch_domain_models::router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }; +pub use hyperswitch_interfaces::api::payouts::{ + PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient, + PayoutRecipientAccount, PayoutSync, +}; pub use super::payouts_v2::{ PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2, PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2, PayoutsV2, }; -use crate::{services::api, types}; - -pub trait PayoutCancel: - api::ConnectorIntegration<PoCancel, types::PayoutsData, types::PayoutsResponseData> -{ -} - -pub trait PayoutCreate: - api::ConnectorIntegration<PoCreate, types::PayoutsData, types::PayoutsResponseData> -{ -} - -pub trait PayoutEligibility: - api::ConnectorIntegration<PoEligibility, types::PayoutsData, types::PayoutsResponseData> -{ -} - -pub trait PayoutFulfill: - api::ConnectorIntegration<PoFulfill, types::PayoutsData, types::PayoutsResponseData> -{ -} - -pub trait PayoutQuote: - api::ConnectorIntegration<PoQuote, types::PayoutsData, types::PayoutsResponseData> -{ -} - -pub trait PayoutRecipient: - api::ConnectorIntegration<PoRecipient, types::PayoutsData, types::PayoutsResponseData> -{ -} - -pub trait PayoutRecipientAccount: - api::ConnectorIntegration<PoRecipientAccount, types::PayoutsData, types::PayoutsResponseData> -{ -} - -pub trait PayoutSync: - api::ConnectorIntegration<PoSync, types::PayoutsData, types::PayoutsResponseData> -{ -} diff --git a/crates/router/src/types/api/payouts_v2.rs b/crates/router/src/types/api/payouts_v2.rs index c204bb9798a..00a451e772b 100644 --- a/crates/router/src/types/api/payouts_v2.rs +++ b/crates/router/src/types/api/payouts_v2.rs @@ -7,91 +7,12 @@ pub use api_models::payouts::{ pub use hyperswitch_domain_models::router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }; - -use crate::{ - services::api, - types::{self, api as api_types}, +pub use hyperswitch_interfaces::api::payouts_v2::{ + PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2, + PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2, }; -pub trait PayoutCancelV2: - api::ConnectorIntegrationV2< - PoCancel, - types::PayoutFlowData, - types::PayoutsData, - types::PayoutsResponseData, -> -{ -} - -pub trait PayoutCreateV2: - api::ConnectorIntegrationV2< - PoCreate, - types::PayoutFlowData, - types::PayoutsData, - types::PayoutsResponseData, -> -{ -} - -pub trait PayoutEligibilityV2: - api::ConnectorIntegrationV2< - PoEligibility, - types::PayoutFlowData, - types::PayoutsData, - types::PayoutsResponseData, -> -{ -} - -pub trait PayoutFulfillV2: - api::ConnectorIntegrationV2< - PoFulfill, - types::PayoutFlowData, - types::PayoutsData, - types::PayoutsResponseData, -> -{ -} - -pub trait PayoutQuoteV2: - api::ConnectorIntegrationV2< - PoQuote, - types::PayoutFlowData, - types::PayoutsData, - types::PayoutsResponseData, -> -{ -} - -pub trait PayoutRecipientV2: - api::ConnectorIntegrationV2< - PoRecipient, - types::PayoutFlowData, - types::PayoutsData, - types::PayoutsResponseData, -> -{ -} - -pub trait PayoutRecipientAccountV2: - api::ConnectorIntegrationV2< - PoRecipientAccount, - types::PayoutFlowData, - types::PayoutsData, - types::PayoutsResponseData, -> -{ -} - -pub trait PayoutSyncV2: - api::ConnectorIntegrationV2< - PoSync, - types::PayoutFlowData, - types::PayoutsData, - types::PayoutsResponseData, -> -{ -} +use crate::types::api as api_types; pub trait PayoutsV2: api_types::ConnectorCommon diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index 67ca7cbfc45..7aafe4de152 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -3,13 +3,9 @@ pub use api_models::refunds::{ RefundsRetrieveRequest, }; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; +pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync}; -pub use super::refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2}; -use super::ConnectorCommon; -use crate::{ - services::api, - types::{self, storage::enums as storage_enums, transformers::ForeignFrom}, -}; +use crate::types::{storage::enums as storage_enums, transformers::ForeignFrom}; impl ForeignFrom<storage_enums::RefundStatus> for RefundStatus { fn foreign_from(status: storage_enums::RefundStatus) -> Self { @@ -22,15 +18,3 @@ impl ForeignFrom<storage_enums::RefundStatus> for RefundStatus { } } } - -pub trait RefundExecute: - api::ConnectorIntegration<Execute, types::RefundsData, types::RefundsResponseData> -{ -} - -pub trait RefundSync: - api::ConnectorIntegration<RSync, types::RefundsData, types::RefundsResponseData> -{ -} - -pub trait Refund: ConnectorCommon + RefundExecute + RefundSync {} diff --git a/crates/router/src/types/api/refunds_v2.rs b/crates/router/src/types/api/refunds_v2.rs index d0e3e8db29e..49db7be9433 100644 --- a/crates/router/src/types/api/refunds_v2.rs +++ b/crates/router/src/types/api/refunds_v2.rs @@ -1,18 +1 @@ -use hyperswitch_domain_models::{ - router_data_v2::flow_common_types::RefundFlowData, - router_flow_types::refunds::{Execute, RSync}, -}; - -use super::ConnectorCommon; -use crate::{services::api, types}; -pub trait RefundExecuteV2: - api::ConnectorIntegrationV2<Execute, RefundFlowData, types::RefundsData, types::RefundsResponseData> -{ -} - -pub trait RefundSyncV2: - api::ConnectorIntegrationV2<RSync, RefundFlowData, types::RefundsData, types::RefundsResponseData> -{ -} - -pub trait RefundV2: ConnectorCommon + RefundExecuteV2 + RefundSyncV2 {} +pub use hyperswitch_interfaces::api::refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2};
2024-07-11T08:53:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Move connector code for `helcim` from crate `router` to new crate `hyperswitch_connectors`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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/5289 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Following flows need to be tested for connector Helcim 1. Authorize: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_EvozwXY09n7tTs0SbWXKKGuEBIAtODBGwPTeu4iDlCx8izBWqyOF5QCNjPccy5qV' \ --data '{ "amount": 1742, "currency": "USD", "confirm": true, "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "setup_future_usage": "on_session", "payment_method_data": { "card": { "card_number": "5413330089099130", "card_exp_month": "01", "card_exp_year": "27", "card_cvc": "123", "card_holder_name": "John Doe" } }, "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" }, "billing": { "address": { "line1": "casd", "zip": "94122", "first_name": "John", "last_name": "Doe" } }, "customer_id": "chethan" }' ``` Response: ``` { "payment_id": "pay_TCUn15IkjNK5RVJvhkVQ", "merchant_id": "merchant_1721640890", "status": "succeeded", "amount": 1742, "net_amount": 1742, "amount_capturable": 0, "amount_received": 1742, "connector": "helcim", "client_secret": "pay_TCUn15IkjNK5RVJvhkVQ_secret_vw61UKv9fMjFtLLIqvxP", "created": "2024-07-24T09:52:40.945Z", "currency": "USD", "customer_id": "chethan", "customer": { "id": "chethan", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "9130", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "541333", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "27", "card_holder_name": "John Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": "casd", "line2": null, "line3": null, "zip": "94122", "state": null, "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "chethan", "created_at": 1721814760, "expires": 1721818360, "secret": "epk_fff23eaae15744eda3e21f25da60d9c5" }, "manual_retry_allowed": false, "connector_transaction_id": "27216935", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_TCUn15IkjNK5RVJvhkVQ_1", "payment_link": null, "profile_id": "pro_LFHne2pOYzWQinLzkwCx", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_x6fFNn94BtH7q72XabAM", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-24T10:07:40.944Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-24T09:52:43.689Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` 2. Capture: Request: ``` curl --location 'http://localhost:8080/payments/pay_ocZh7RY06eyLv1cRi4O5/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_EvozwXY09n7tTs0SbWXKKGuEBIAtODBGwPTeu4iDlCx8izBWqyOF5QCNjPccy5qV' \ --data '{ }' ``` Response: ``` { "payment_id": "pay_ocZh7RY06eyLv1cRi4O5", "merchant_id": "merchant_1721640890", "status": "succeeded", "amount": 1742, "net_amount": 1742, "amount_capturable": 0, "amount_received": 1742, "connector": "helcim", "client_secret": "pay_ocZh7RY06eyLv1cRi4O5_secret_w59OCpVfwMQtbfFEN7Nd", "created": "2024-07-24T09:54:19.891Z", "currency": "USD", "customer_id": "chethan", "customer": { "id": "chethan", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "9130", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "541333", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "27", "card_holder_name": "John Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": "casd", "line2": null, "line3": null, "zip": "94122", "state": null, "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "27216940", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "", "payment_link": null, "profile_id": "pro_LFHne2pOYzWQinLzkwCx", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_x6fFNn94BtH7q72XabAM", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-24T10:09:19.891Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-24T09:54:34.462Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
26b878308f7e493d6adb8c08b54a5498406eb28a
juspay/hyperswitch
juspay__hyperswitch-5255
Bug: Removal of routing_metadata Logs ### Bug Description The logs about the field not being deserialized was being spammed. ### Expected Behavior It should do a checked deserialization of the metadata. ### Actual Behavior It is spamming logs for every payments. ### Steps To Reproduce 1. Configure routing rules 2. Make a payment 3. Check logs ### 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/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 8c27e3b3cac..d1a5441d958 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -115,10 +115,7 @@ pub fn make_dsl_input_for_payouts( .transpose() .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payouts") - .unwrap_or_else(|err| { - logger::error!(error=?err); - None - }); + .unwrap_or(None); let payment = dsl_inputs::PaymentInput { amount: payout_data.payouts.amount, card_bin: None, @@ -249,10 +246,7 @@ where .transpose() .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payment_intent") - .unwrap_or_else(|err| { - logger::error!(error=?err); - None - }); + .unwrap_or(None); Ok(dsl_inputs::BackendInput { metadata, @@ -937,10 +931,7 @@ pub async fn perform_session_flow_routing( .transpose() .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payment_intent") - .unwrap_or_else(|err| { - logger::error!(?err); - None - }); + .unwrap_or(None); let mut backend_input = dsl_inputs::BackendInput { metadata, @@ -1166,10 +1157,7 @@ pub fn make_dsl_input_for_surcharge( .transpose() .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payment_intent") - .unwrap_or_else(|err| { - logger::error!(error=?err); - None - }); + .unwrap_or(None); let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: None, payment_method_type: None,
2024-07-09T09:37:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Removal of metadata_parsing logs, as it was being spammed a lot of times. Moreover soon a method for proper deserialization by either String match or conversion of the hashMap to typed will be done. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We are just removing logs in this PR. No extra code/flow changes. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
fa83b697ab104e8e161170c9251c28b1aab1c890
juspay/hyperswitch
juspay__hyperswitch-5335
Bug: [FEATURE]: Integrate encryption service with hyperswitch ### Feature Description PCI compliance requires application to follow some standards where encryption and decryption should not happen within the application as snapshot might have DEK and data together. So separate service should be used for encryption and decryption. In application wherever we are calling encrypt and decrypt it will be replaced by API call to encryption service. ### Possible Implementation replace all internal encryption and decryption implementation with API call to encryption service ### 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 193f19453b9..66b38d09c1f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2006,6 +2006,7 @@ name = "common_utils" version = "0.1.0" dependencies = [ "async-trait", + "base64 0.22.0", "blake3", "bytes 1.6.0", "common_enums", @@ -2704,6 +2705,7 @@ dependencies = [ "masking", "router_derive", "router_env", + "rustc-hash", "serde", "serde_json", "strum 0.26.2", @@ -3858,6 +3860,7 @@ dependencies = [ "mime", "router_derive", "router_env", + "rustc-hash", "serde", "serde_json", "serde_with", diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index 37c4cd0f1b8..73fb5264ed9 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -1,5 +1,12 @@ -use common_utils::{crypto, custom_serde, id_type, pii}; -use masking::Secret; +use common_utils::{ + crypto, custom_serde, + encryption::Encryption, + id_type, + pii::{self, EmailStrategy}, + types::keymanager::ToEncryptable, +}; +use euclid::dssa::graph::euclid_graph_prelude::FxHashMap; +use masking::{ExposeInterface, Secret, SwitchStrategy}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -40,6 +47,85 @@ pub struct CustomerRequest { pub metadata: Option<pii::SecretSerdeValue>, } +pub struct CustomerRequestWithEmail { + pub name: Option<Secret<String>>, + pub email: Option<pii::Email>, + pub phone: Option<Secret<String>>, +} + +pub struct CustomerRequestWithEncryption { + pub name: Option<Encryption>, + pub phone: Option<Encryption>, + pub email: Option<Encryption>, +} + +pub struct EncryptableCustomer { + pub name: crypto::OptionalEncryptableName, + pub phone: crypto::OptionalEncryptablePhone, + pub email: crypto::OptionalEncryptableEmail, +} + +impl ToEncryptable<EncryptableCustomer, Secret<String>, Encryption> + for CustomerRequestWithEncryption +{ + fn to_encryptable(self) -> FxHashMap<String, Encryption> { + let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); + self.name.map(|x| map.insert("name".to_string(), x)); + self.phone.map(|x| map.insert("phone".to_string(), x)); + self.email.map(|x| map.insert("email".to_string(), x)); + map + } + + fn from_encryptable( + mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>, + ) -> common_utils::errors::CustomResult<EncryptableCustomer, common_utils::errors::ParsingError> + { + Ok(EncryptableCustomer { + name: hashmap.remove("name"), + phone: hashmap.remove("phone"), + email: hashmap.remove("email").map(|email| { + let encryptable: crypto::Encryptable<Secret<String, EmailStrategy>> = + crypto::Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), + }) + } +} + +impl ToEncryptable<EncryptableCustomer, Secret<String>, Secret<String>> + for CustomerRequestWithEmail +{ + fn to_encryptable(self) -> FxHashMap<String, Secret<String>> { + let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); + self.name.map(|x| map.insert("name".to_string(), x)); + self.phone.map(|x| map.insert("phone".to_string(), x)); + self.email + .map(|x| map.insert("email".to_string(), x.expose().switch_strategy())); + map + } + + fn from_encryptable( + mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>, + ) -> common_utils::errors::CustomResult<EncryptableCustomer, common_utils::errors::ParsingError> + { + Ok(EncryptableCustomer { + name: hashmap.remove("name"), + email: hashmap.remove("email").map(|email| { + let encryptable: crypto::Encryptable<Secret<String, EmailStrategy>> = + crypto::Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), + phone: hashmap.remove("phone"), + }) + } +} + #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// The identifier for the customer object diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 619f345a333..5ac8d0edcc3 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -11,10 +11,11 @@ use common_utils::{ ext_traits::{ConfigExt, Encode}, hashing::HashedString, id_type, - pii::{self, Email}, - types::{MinorUnit, StringMajorUnit}, + pii::{self, Email, EmailStrategy}, + types::{keymanager::ToEncryptable, MinorUnit, StringMajorUnit}, }; -use masking::{PeekInterface, Secret, WithType}; +use euclid::dssa::graph::euclid_graph_prelude::FxHashMap; +use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy, WithType}; use router_derive::Setter; use serde::{ de::{self, Unexpected, Visitor}, @@ -3187,6 +3188,72 @@ impl AddressDetails { } } +pub struct AddressDetailsWithPhone { + pub address: Option<AddressDetails>, + pub phone_number: Option<Secret<String>>, + pub email: Option<Email>, +} + +pub struct EncryptableAddressDetails { + pub line1: crypto::OptionalEncryptableSecretString, + pub line2: crypto::OptionalEncryptableSecretString, + pub line3: crypto::OptionalEncryptableSecretString, + pub state: crypto::OptionalEncryptableSecretString, + pub zip: crypto::OptionalEncryptableSecretString, + pub first_name: crypto::OptionalEncryptableSecretString, + pub last_name: crypto::OptionalEncryptableSecretString, + pub phone_number: crypto::OptionalEncryptableSecretString, + pub email: crypto::OptionalEncryptableEmail, +} + +impl ToEncryptable<EncryptableAddressDetails, Secret<String>, Secret<String>> + for AddressDetailsWithPhone +{ + fn from_encryptable( + mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>, + ) -> common_utils::errors::CustomResult< + EncryptableAddressDetails, + common_utils::errors::ParsingError, + > { + Ok(EncryptableAddressDetails { + line1: hashmap.remove("line1"), + line2: hashmap.remove("line2"), + line3: hashmap.remove("line3"), + state: hashmap.remove("state"), + zip: hashmap.remove("zip"), + first_name: hashmap.remove("first_name"), + last_name: hashmap.remove("last_name"), + phone_number: hashmap.remove("phone_number"), + email: hashmap.remove("email").map(|x| { + let inner: Secret<String, EmailStrategy> = x.clone().into_inner().switch_strategy(); + crypto::Encryptable::new(inner, x.into_encrypted()) + }), + }) + } + + fn to_encryptable(self) -> FxHashMap<String, Secret<String>> { + let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default()); + self.address.map(|address| { + address.line1.map(|x| map.insert("line1".to_string(), x)); + address.line2.map(|x| map.insert("line2".to_string(), x)); + address.line3.map(|x| map.insert("line3".to_string(), x)); + address.state.map(|x| map.insert("state".to_string(), x)); + address.zip.map(|x| map.insert("zip".to_string(), x)); + address + .first_name + .map(|x| map.insert("first_name".to_string(), x)); + address + .last_name + .map(|x| map.insert("last_name".to_string(), x)); + }); + self.email + .map(|x| map.insert("email".to_string(), x.expose().switch_strategy())); + self.phone_number + .map(|x| map.insert("phone_number".to_string(), x)); + map + } +} + #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index df6b4400633..61d96a21737 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [features] keymanager = ["dep:router_env"] keymanager_mtls = ["reqwest/rustls-tls"] +encryption_service = ["dep:router_env"] signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_env", "dep:futures"] async_ext = ["dep:async-trait", "dep:futures"] logs = ["dep:router_env"] @@ -17,6 +18,7 @@ metrics = ["dep:router_env", "dep:futures"] [dependencies] async-trait = { version = "0.1.79", optional = true } +base64 = "0.22.0" blake3 = { version = "1.5.1", features = ["serde"] } bytes = "1.6.0" diesel = "2.1.5" diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 848189cd899..e52d24c9baa 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -99,6 +99,8 @@ pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64; /// Minimum allowed length for MerchantReferenceId pub const MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 1; +/// General purpose base64 engine +pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; /// Regex for matching a domain /// Eg - /// http://www.example.com diff --git a/crates/diesel_models/src/encryption.rs b/crates/common_utils/src/encryption.rs similarity index 88% rename from crates/diesel_models/src/encryption.rs rename to crates/common_utils/src/encryption.rs index 6c6063c1604..9c566432782 100644 --- a/crates/diesel_models/src/encryption.rs +++ b/crates/common_utils/src/encryption.rs @@ -1,40 +1,13 @@ -use common_utils::pii::EncryptionStrategy; use diesel::{ backend::Backend, deserialize::{self, FromSql, Queryable}, + expression::AsExpression, serialize::ToSql, - sql_types, AsExpression, + sql_types, }; use masking::Secret; -#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] -#[diesel(sql_type = sql_types::Binary)] -#[repr(transparent)] -pub struct Encryption { - inner: Secret<Vec<u8>, EncryptionStrategy>, -} - -impl<T: Clone> From<common_utils::crypto::Encryptable<T>> for Encryption { - fn from(value: common_utils::crypto::Encryptable<T>) -> Self { - Self::new(value.into_encrypted()) - } -} - -impl Encryption { - pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self { - Self { inner: item } - } - - #[inline] - pub fn into_inner(self) -> Secret<Vec<u8>, EncryptionStrategy> { - self.inner - } - - #[inline] - pub fn get_inner(&self) -> &Secret<Vec<u8>, EncryptionStrategy> { - &self.inner - } -} +use crate::{crypto::Encryptable, pii::EncryptionStrategy}; impl<DB> FromSql<sql_types::Binary, DB> for Encryption where @@ -69,3 +42,32 @@ where Ok(Self { inner: row }) } } + +#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] +#[diesel(sql_type = sql_types::Binary)] +#[repr(transparent)] +pub struct Encryption { + inner: Secret<Vec<u8>, EncryptionStrategy>, +} + +impl<T: Clone> From<Encryptable<T>> for Encryption { + fn from(value: Encryptable<T>) -> Self { + Self::new(value.into_encrypted()) + } +} + +impl Encryption { + pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self { + Self { inner: item } + } + + #[inline] + pub fn into_inner(self) -> Secret<Vec<u8>, EncryptionStrategy> { + self.inner + } + + #[inline] + pub fn get_inner(&self) -> &Secret<Vec<u8>, EncryptionStrategy> { + &self.inner + } +} diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rs index ecdb9b63ad5..9d6e9315074 100644 --- a/crates/common_utils/src/keymanager.rs +++ b/crates/common_utils/src/keymanager.rs @@ -3,22 +3,26 @@ use core::fmt::Debug; use std::str::FromStr; +use base64::Engine; use error_stack::ResultExt; use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; -#[cfg(feature = "keymanager_mtls")] -use masking::PeekInterface; +use masking::{PeekInterface, StrongSecret}; use once_cell::sync::OnceCell; use router_env::{instrument, logger, tracing}; use crate::{ + consts::BASE64_ENGINE, errors, types::keymanager::{ - DataKeyCreateResponse, EncryptionCreateRequest, EncryptionTransferRequest, KeyManagerState, + BatchDecryptDataRequest, DataKeyCreateResponse, DecryptDataRequest, + EncryptionCreateRequest, EncryptionTransferRequest, KeyManagerState, + TransientBatchDecryptDataRequest, TransientDecryptDataRequest, }, }; const CONTENT_TYPE: &str = "Content-Type"; static ENCRYPTION_API_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); +static DEFAULT_ENCRYPTION_VERSION: &str = "v1"; /// Get keymanager client constructed from the url and state #[instrument(skip_all)] @@ -68,7 +72,7 @@ pub async fn send_encryption_request<T>( request_body: T, ) -> errors::CustomResult<reqwest::Response, errors::KeyManagerClientError> where - T: serde::Serialize, + T: ConvertRaw, { let client = get_api_encryption_client(state)?; let url = reqwest::Url::parse(&url) @@ -76,7 +80,7 @@ where client .request(method, url) - .json(&request_body) + .json(&ConvertRaw::convert_raw(request_body)?) .headers(headers) .send() .await @@ -94,7 +98,7 @@ pub async fn call_encryption_service<T, R>( request_body: T, ) -> errors::CustomResult<R, errors::KeyManagerClientError> where - T: serde::Serialize + Send + Sync + 'static + Debug, + T: ConvertRaw + Send + Sync + 'static + Debug, R: serde::de::DeserializeOwned, { let url = format!("{}/{endpoint}", &state.url); @@ -152,6 +156,62 @@ where } } +/// Trait to convert the raw data to the required format for encryption service request +pub trait ConvertRaw { + /// Return type of the convert_raw function + type Output: serde::Serialize; + /// Function to convert the raw data to the required format for encryption service request + fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError>; +} + +impl<T: serde::Serialize> ConvertRaw for T { + type Output = T; + fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { + Ok(self) + } +} + +impl ConvertRaw for TransientDecryptDataRequest { + type Output = DecryptDataRequest; + fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { + let data = match String::from_utf8(self.data.peek().clone()) { + Ok(data) => data, + Err(_) => { + let data = BASE64_ENGINE.encode(self.data.peek().clone()); + format!("{DEFAULT_ENCRYPTION_VERSION}:{data}") + } + }; + Ok(DecryptDataRequest { + identifier: self.identifier, + data: StrongSecret::new(data), + }) + } +} + +impl ConvertRaw for TransientBatchDecryptDataRequest { + type Output = BatchDecryptDataRequest; + fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { + let data = self + .data + .iter() + .map(|(k, v)| { + let value = match String::from_utf8(v.peek().clone()) { + Ok(data) => data, + Err(_) => { + let data = BASE64_ENGINE.encode(v.peek().clone()); + format!("{DEFAULT_ENCRYPTION_VERSION}:{data}") + } + }; + (k.to_owned(), StrongSecret::new(value)) + }) + .collect(); + Ok(BatchDecryptDataRequest { + data, + identifier: self.identifier, + }) + } +} + /// A function to create the key in keymanager #[instrument(skip_all)] pub async fn create_key_in_key_manager( diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 9b339fb956e..e93b0c66ceb 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -13,6 +13,8 @@ pub mod access_token; pub mod consts; pub mod crypto; pub mod custom_serde; +#[allow(missing_docs)] // Todo: add docs +pub mod encryption; pub mod errors; #[allow(missing_docs)] // Todo: add docs pub mod events; @@ -31,6 +33,7 @@ pub mod request; pub mod signals; #[allow(missing_docs)] // Todo: add docs pub mod static_cache; +pub mod transformers; pub mod types; pub mod validation; diff --git a/crates/common_utils/src/transformers.rs b/crates/common_utils/src/transformers.rs new file mode 100644 index 00000000000..3799522e16d --- /dev/null +++ b/crates/common_utils/src/transformers.rs @@ -0,0 +1,15 @@ +//! Utilities for converting between foreign types + +/// Trait for converting from one foreign type to another +pub trait ForeignFrom<F> { + /// Convert from a foreign type to the current type + fn foreign_from(from: F) -> Self; +} + +/// Trait for converting from one foreign type to another +pub trait ForeignTryFrom<F>: Sized { + /// Custom error for conversion failure + type Error; + /// Convert from a foreign type to the current type and return an error if the conversion fails + fn foreign_try_from(from: F) -> Result<Self, Self::Error>; +} diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs index 356ccdd4832..5a7b87d0ce0 100644 --- a/crates/common_utils/src/types/keymanager.rs +++ b/crates/common_utils/src/types/keymanager.rs @@ -1,8 +1,24 @@ #![allow(missing_docs)] -#[cfg(feature = "keymanager_mtls")] -use masking::Secret; -use serde::{Deserialize, Serialize}; +use core::fmt; + +use base64::Engine; +use masking::{ExposeInterface, PeekInterface, Secret, Strategy, StrongSecret}; +#[cfg(feature = "encryption_service")] +use router_env::logger; +use rustc_hash::FxHashMap; +use serde::{ + de::{self, Unexpected, Visitor}, + ser, Deserialize, Deserializer, Serialize, +}; + +use crate::{ + consts::BASE64_ENGINE, + crypto::Encryptable, + encryption::Encryption, + errors::{self, CustomResult}, + transformers::{ForeignFrom, ForeignTryFrom}, +}; #[derive(Debug)] pub struct KeyManagerState { @@ -18,6 +34,7 @@ pub struct KeyManagerState { pub enum Identifier { User(String), Merchant(String), + UserAuth(String), } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] @@ -39,3 +56,420 @@ pub struct DataKeyCreateResponse { pub identifier: Identifier, pub key_version: String, } + +#[derive(Serialize, Deserialize, Debug)] +pub struct BatchEncryptDataRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub data: DecryptedDataGroup, +} + +impl<S> From<(Secret<Vec<u8>, S>, Identifier)> for EncryptDataRequest +where + S: Strategy<Vec<u8>>, +{ + fn from((secret, identifier): (Secret<Vec<u8>, S>, Identifier)) -> Self { + Self { + identifier, + data: DecryptedData(StrongSecret::new(secret.expose())), + } + } +} + +impl<S> From<(FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)> for BatchEncryptDataRequest +where + S: Strategy<Vec<u8>>, +{ + fn from((map, identifier): (FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)) -> Self { + let group = map + .into_iter() + .map(|(key, value)| (key, DecryptedData(StrongSecret::new(value.expose())))) + .collect(); + Self { + identifier, + data: DecryptedDataGroup(group), + } + } +} + +impl<S> From<(Secret<String, S>, Identifier)> for EncryptDataRequest +where + S: Strategy<String>, +{ + fn from((secret, identifier): (Secret<String, S>, Identifier)) -> Self { + Self { + data: DecryptedData(StrongSecret::new(secret.expose().as_bytes().to_vec())), + identifier, + } + } +} + +impl<S> From<(Secret<serde_json::Value, S>, Identifier)> for EncryptDataRequest +where + S: Strategy<serde_json::Value>, +{ + fn from((secret, identifier): (Secret<serde_json::Value, S>, Identifier)) -> Self { + Self { + data: DecryptedData(StrongSecret::new( + secret.expose().to_string().as_bytes().to_vec(), + )), + identifier, + } + } +} + +impl<S> From<(FxHashMap<String, Secret<serde_json::Value, S>>, Identifier)> + for BatchEncryptDataRequest +where + S: Strategy<serde_json::Value>, +{ + fn from( + (map, identifier): (FxHashMap<String, Secret<serde_json::Value, S>>, Identifier), + ) -> Self { + let group = map + .into_iter() + .map(|(key, value)| { + ( + key, + DecryptedData(StrongSecret::new( + value.expose().to_string().as_bytes().to_vec(), + )), + ) + }) + .collect(); + Self { + data: DecryptedDataGroup(group), + identifier, + } + } +} + +impl<S> From<(FxHashMap<String, Secret<String, S>>, Identifier)> for BatchEncryptDataRequest +where + S: Strategy<String>, +{ + fn from((map, identifier): (FxHashMap<String, Secret<String, S>>, Identifier)) -> Self { + let group = map + .into_iter() + .map(|(key, value)| { + ( + key, + DecryptedData(StrongSecret::new(value.expose().as_bytes().to_vec())), + ) + }) + .collect(); + Self { + data: DecryptedDataGroup(group), + identifier, + } + } +} + +#[derive(Serialize, Deserialize, Debug)] +pub struct EncryptDataRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub data: DecryptedData, +} + +#[derive(Debug, Serialize, serde::Deserialize)] +pub struct DecryptedDataGroup(pub FxHashMap<String, DecryptedData>); + +#[derive(Debug, Serialize, Deserialize)] +pub struct BatchEncryptDataResponse { + pub data: EncryptedDataGroup, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct EncryptDataResponse { + pub data: EncryptedData, +} + +#[derive(Debug, Serialize, serde::Deserialize)] +pub struct EncryptedDataGroup(pub FxHashMap<String, EncryptedData>); +#[derive(Debug)] +pub struct TransientBatchDecryptDataRequest { + pub identifier: Identifier, + pub data: FxHashMap<String, StrongSecret<Vec<u8>>>, +} + +#[derive(Debug)] +pub struct TransientDecryptDataRequest { + pub identifier: Identifier, + pub data: StrongSecret<Vec<u8>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct BatchDecryptDataRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub data: FxHashMap<String, StrongSecret<String>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct DecryptDataRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub data: StrongSecret<String>, +} + +impl<T, S> ForeignFrom<(FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse)> + for FxHashMap<String, Encryptable<Secret<T, S>>> +where + T: Clone, + S: Strategy<T> + Send, +{ + fn foreign_from( + (mut masked_data, response): (FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse), + ) -> Self { + response + .data + .0 + .into_iter() + .flat_map(|(k, v)| { + masked_data.remove(&k).map(|inner| { + ( + k, + Encryptable::new(inner.clone(), v.data.peek().clone().into()), + ) + }) + }) + .collect() + } +} + +impl<T, S> ForeignFrom<(Secret<T, S>, EncryptDataResponse)> for Encryptable<Secret<T, S>> +where + T: Clone, + S: Strategy<T> + Send, +{ + fn foreign_from((masked_data, response): (Secret<T, S>, EncryptDataResponse)) -> Self { + Self::new(masked_data, response.data.data.peek().clone().into()) + } +} + +pub trait DecryptedDataConversion<T: Clone, S: Strategy<T> + Send>: Sized { + fn convert( + value: &DecryptedData, + encryption: Encryption, + ) -> CustomResult<Self, errors::CryptoError>; +} + +impl<S: Strategy<String> + Send> DecryptedDataConversion<String, S> + for Encryptable<Secret<String, S>> +{ + fn convert( + value: &DecryptedData, + encryption: Encryption, + ) -> CustomResult<Self, errors::CryptoError> { + let string = String::from_utf8(value.clone().inner().peek().clone()).map_err(|_err| { + #[cfg(feature = "encryption_service")] + logger::error!("Decryption error {:?}", _err); + errors::CryptoError::DecodingFailed + })?; + Ok(Self::new(Secret::new(string), encryption.into_inner())) + } +} + +impl<S: Strategy<serde_json::Value> + Send> DecryptedDataConversion<serde_json::Value, S> + for Encryptable<Secret<serde_json::Value, S>> +{ + fn convert( + value: &DecryptedData, + encryption: Encryption, + ) -> CustomResult<Self, errors::CryptoError> { + let val = serde_json::from_slice(value.clone().inner().peek()).map_err(|_err| { + #[cfg(feature = "encryption_service")] + logger::error!("Decryption error {:?}", _err); + errors::CryptoError::DecodingFailed + })?; + Ok(Self::new(Secret::new(val), encryption.clone().into_inner())) + } +} + +impl<S: Strategy<Vec<u8>> + Send> DecryptedDataConversion<Vec<u8>, S> + for Encryptable<Secret<Vec<u8>, S>> +{ + fn convert( + value: &DecryptedData, + encryption: Encryption, + ) -> CustomResult<Self, errors::CryptoError> { + Ok(Self::new( + Secret::new(value.clone().inner().peek().clone()), + encryption.clone().into_inner(), + )) + } +} + +impl<T, S> ForeignTryFrom<(Encryption, DecryptDataResponse)> for Encryptable<Secret<T, S>> +where + T: Clone, + S: Strategy<T> + Send, + Self: DecryptedDataConversion<T, S>, +{ + type Error = error_stack::Report<errors::CryptoError>; + fn foreign_try_from( + (encrypted_data, response): (Encryption, DecryptDataResponse), + ) -> Result<Self, Self::Error> { + Self::convert(&response.data, encrypted_data) + } +} + +impl<T, S> ForeignTryFrom<(FxHashMap<String, Encryption>, BatchDecryptDataResponse)> + for FxHashMap<String, Encryptable<Secret<T, S>>> +where + T: Clone, + S: Strategy<T> + Send, + Encryptable<Secret<T, S>>: DecryptedDataConversion<T, S>, +{ + type Error = error_stack::Report<errors::CryptoError>; + fn foreign_try_from( + (mut encrypted_data, response): (FxHashMap<String, Encryption>, BatchDecryptDataResponse), + ) -> Result<Self, Self::Error> { + response + .data + .0 + .into_iter() + .map(|(k, v)| match encrypted_data.remove(&k) { + Some(encrypted) => Ok((k.clone(), Encryptable::convert(&v, encrypted.clone())?)), + None => Err(errors::CryptoError::DecodingFailed)?, + }) + .collect() + } +} + +impl From<(Encryption, Identifier)> for TransientDecryptDataRequest { + fn from((encryption, identifier): (Encryption, Identifier)) -> Self { + Self { + data: StrongSecret::new(encryption.clone().into_inner().expose()), + identifier, + } + } +} + +impl From<(FxHashMap<String, Encryption>, Identifier)> for TransientBatchDecryptDataRequest { + fn from((map, identifier): (FxHashMap<String, Encryption>, Identifier)) -> Self { + let data = map + .into_iter() + .map(|(k, v)| (k, StrongSecret::new(v.clone().into_inner().expose()))) + .collect(); + Self { data, identifier } + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct BatchDecryptDataResponse { + pub data: DecryptedDataGroup, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct DecryptDataResponse { + pub data: DecryptedData, +} + +#[derive(Clone, Debug)] +pub struct DecryptedData(StrongSecret<Vec<u8>>); + +impl Serialize for DecryptedData { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + let data = BASE64_ENGINE.encode(self.0.peek()); + serializer.serialize_str(&data) + } +} + +impl<'de> Deserialize<'de> for DecryptedData { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct DecryptedDataVisitor; + + impl<'de> Visitor<'de> for DecryptedDataVisitor { + type Value = DecryptedData; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("string of the format {version}:{base64_encoded_data}'") + } + + fn visit_str<E>(self, value: &str) -> Result<DecryptedData, E> + where + E: de::Error, + { + let dec_data = BASE64_ENGINE.decode(value).map_err(|err| { + let err = err.to_string(); + E::invalid_value(Unexpected::Str(value), &err.as_str()) + })?; + + Ok(DecryptedData(dec_data.into())) + } + } + + deserializer.deserialize_str(DecryptedDataVisitor) + } +} + +impl DecryptedData { + pub fn from_data(data: StrongSecret<Vec<u8>>) -> Self { + Self(data) + } + + pub fn inner(self) -> StrongSecret<Vec<u8>> { + self.0 + } +} + +#[derive(Debug)] +pub struct EncryptedData { + pub data: StrongSecret<Vec<u8>>, +} + +impl Serialize for EncryptedData { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + let data = String::from_utf8(self.data.peek().clone()).map_err(ser::Error::custom)?; + serializer.serialize_str(data.as_str()) + } +} + +impl<'de> Deserialize<'de> for EncryptedData { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct EncryptedDataVisitor; + + impl<'de> Visitor<'de> for EncryptedDataVisitor { + type Value = EncryptedData; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("string of the format {version}:{base64_encoded_data}'") + } + + fn visit_str<E>(self, value: &str) -> Result<EncryptedData, E> + where + E: de::Error, + { + Ok(EncryptedData { + data: StrongSecret::new(value.as_bytes().to_vec()), + }) + } + } + + deserializer.deserialize_str(EncryptedDataVisitor) + } +} + +/// A trait which converts the struct to Hashmap required for encryption and back to struct +pub trait ToEncryptable<T, S: Clone, E>: Sized { + /// Serializes the type to a hashmap + fn to_encryptable(self) -> FxHashMap<String, E>; + /// Deserializes the hashmap back to the type + fn from_encryptable( + hashmap: FxHashMap<String, Encryptable<S>>, + ) -> CustomResult<T, errors::ParsingError>; +} diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index f33427aaf30..10890ef0cf0 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -15,6 +15,7 @@ kv_store = [] async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } diesel = { version = "2.1.5", features = ["postgres", "serde_json", "time", "64-column-tables"] } error-stack = "0.4.1" +rustc-hash = "1.1.0" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26.2", features = ["derive"] } diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs index d695d2a0e70..57c4e36c786 100644 --- a/crates/diesel_models/src/address.rs +++ b/crates/diesel_models/src/address.rs @@ -1,9 +1,17 @@ -use common_utils::id_type; +use common_utils::{ + crypto::{self, Encryptable}, + encryption::Encryption, + id_type, + pii::EmailStrategy, + types::keymanager::ToEncryptable, +}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; +use masking::{Secret, SwitchStrategy}; +use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums, schema::address}; +use crate::{enums, schema::address}; #[derive(Clone, Debug, Insertable, Serialize, Deserialize, router_derive::DebugAsDisplay)] #[diesel(table_name = address)] @@ -54,6 +62,62 @@ pub struct Address { pub email: Option<Encryption>, } +#[derive(Clone)] +// Intermediate struct to convert HashMap to Address +pub struct EncryptableAddress { + pub line1: crypto::OptionalEncryptableSecretString, + pub line2: crypto::OptionalEncryptableSecretString, + pub line3: crypto::OptionalEncryptableSecretString, + pub state: crypto::OptionalEncryptableSecretString, + pub zip: crypto::OptionalEncryptableSecretString, + pub first_name: crypto::OptionalEncryptableSecretString, + pub last_name: crypto::OptionalEncryptableSecretString, + pub phone_number: crypto::OptionalEncryptableSecretString, + pub email: crypto::OptionalEncryptableEmail, +} + +impl ToEncryptable<EncryptableAddress, Secret<String>, Encryption> for Address { + fn to_encryptable(self) -> FxHashMap<String, Encryption> { + let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default()); + self.line1.map(|x| map.insert("line1".to_string(), x)); + self.line2.map(|x| map.insert("line2".to_string(), x)); + self.line3.map(|x| map.insert("line3".to_string(), x)); + self.zip.map(|x| map.insert("zip".to_string(), x)); + self.state.map(|x| map.insert("state".to_string(), x)); + self.first_name + .map(|x| map.insert("first_name".to_string(), x)); + self.last_name + .map(|x| map.insert("last_name".to_string(), x)); + self.phone_number + .map(|x| map.insert("phone_number".to_string(), x)); + self.email.map(|x| map.insert("email".to_string(), x)); + map + } + + fn from_encryptable( + mut hashmap: FxHashMap<String, Encryptable<Secret<String>>>, + ) -> common_utils::errors::CustomResult<EncryptableAddress, common_utils::errors::ParsingError> + { + Ok(EncryptableAddress { + line1: hashmap.remove("line1"), + line2: hashmap.remove("line2"), + line3: hashmap.remove("line3"), + zip: hashmap.remove("zip"), + state: hashmap.remove("state"), + first_name: hashmap.remove("first_name"), + last_name: hashmap.remove("last_name"), + phone_number: hashmap.remove("phone_number"), + email: hashmap.remove("email").map(|email| { + let encryptable: Encryptable<Secret<String, EmailStrategy>> = Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), + }) + } +} + #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = address)] pub struct AddressUpdateInternal { diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 6bd1e1f9e41..b964b290a9e 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -1,7 +1,7 @@ -use common_utils::pii; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; -use crate::{encryption::Encryption, schema::business_profile}; +use crate::schema::business_profile; #[derive( Clone, diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index deb1ac73f41..302772b7f9e 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -1,8 +1,8 @@ -use common_utils::{id_type, pii}; +use common_utils::{encryption::Encryption, id_type, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, schema::customers}; +use crate::schema::customers; #[derive( Clone, Debug, Insertable, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs index b3b1230441f..99879dafaf9 100644 --- a/crates/diesel_models/src/events.rs +++ b/crates/diesel_models/src/events.rs @@ -1,11 +1,15 @@ -use common_utils::custom_serde; +use common_utils::{ + crypto::OptionalEncryptableSecretString, custom_serde, encryption::Encryption, + types::keymanager::ToEncryptable, +}; use diesel::{ expression::AsExpression, AsChangeset, Identifiable, Insertable, Queryable, Selectable, }; +use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums as storage_enums, schema::events}; +use crate::{enums as storage_enums, schema::events}; #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = events)] @@ -59,6 +63,38 @@ pub struct Event { pub metadata: Option<EventMetadata>, } +pub struct EventWithEncryption { + pub request: Option<Encryption>, + pub response: Option<Encryption>, +} + +pub struct EncryptableEvent { + pub request: OptionalEncryptableSecretString, + pub response: OptionalEncryptableSecretString, +} + +impl ToEncryptable<EncryptableEvent, Secret<String>, Encryption> for EventWithEncryption { + fn to_encryptable(self) -> rustc_hash::FxHashMap<String, Encryption> { + let mut map = rustc_hash::FxHashMap::default(); + self.request.map(|x| map.insert("request".to_string(), x)); + self.response.map(|x| map.insert("response".to_string(), x)); + map + } + + fn from_encryptable( + mut hashmap: rustc_hash::FxHashMap< + String, + common_utils::crypto::Encryptable<Secret<String>>, + >, + ) -> common_utils::errors::CustomResult<EncryptableEvent, common_utils::errors::ParsingError> + { + Ok(EncryptableEvent { + request: hashmap.remove("request"), + response: hashmap.remove("response"), + }) + } +} + #[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub enum EventMetadata { diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 67061bf6c33..6af1e0e5208 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -12,7 +12,6 @@ pub mod blocklist; pub mod blocklist_fingerprint; pub mod customers; pub mod dispute; -pub mod encryption; pub mod enums; pub mod ephemeral_key; pub mod errors; diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 71c437bbb41..5c48ade55c0 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -1,7 +1,7 @@ -use common_utils::pii; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; -use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_account}; +use crate::{enums as storage_enums, schema::merchant_account}; #[derive( Clone, diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index 05707f71737..5a549892dca 100644 --- a/crates/diesel_models/src/merchant_connector_account.rs +++ b/crates/diesel_models/src/merchant_connector_account.rs @@ -1,10 +1,10 @@ use std::fmt::Debug; -use common_utils::pii; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; -use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_connector_account}; +use crate::{enums as storage_enums, schema::merchant_connector_account}; #[derive( Clone, diff --git a/crates/diesel_models/src/merchant_key_store.rs b/crates/diesel_models/src/merchant_key_store.rs index 30781927e94..b11d9970532 100644 --- a/crates/diesel_models/src/merchant_key_store.rs +++ b/crates/diesel_models/src/merchant_key_store.rs @@ -1,8 +1,8 @@ -use common_utils::custom_serde; +use common_utils::{custom_serde, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, schema::merchant_key_store}; +use crate::schema::merchant_key_store; #[derive( Clone, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 499d72a648a..e4d8dcc315a 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -1,10 +1,10 @@ use common_enums::RequestIncrementalAuthorization; -use common_utils::{id_type, pii, types::MinorUnit}; +use common_utils::{encryption::Encryption, id_type, pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums as storage_enums, schema::payment_intent}; +use crate::{enums as storage_enums, schema::payment_intent}; #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index a9db90abb20..6bb40e4b166 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -1,11 +1,11 @@ use common_enums::MerchantStorageScheme; -use common_utils::{id_type, pii}; +use common_utils::{encryption::Encryption, id_type, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums as storage_enums, schema::payment_methods}; +use crate::{enums as storage_enums, schema::payment_methods}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index 56c6f00f2b0..9d6514916d8 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -1,11 +1,9 @@ -use common_utils::pii; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; -use crate::{ - diesel_impl::OptionalDieselArray, encryption::Encryption, enums::TotpStatus, schema::users, -}; +use crate::{diesel_impl::OptionalDieselArray, enums::TotpStatus, schema::users}; pub mod dashboard_metadata; diff --git a/crates/diesel_models/src/user_authentication_method.rs b/crates/diesel_models/src/user_authentication_method.rs index 18a65b9f104..76e1abe7575 100644 --- a/crates/diesel_models/src/user_authentication_method.rs +++ b/crates/diesel_models/src/user_authentication_method.rs @@ -1,7 +1,8 @@ +use common_utils::encryption::Encryption; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums, schema::user_authentication_methods}; +use crate::{enums, schema::user_authentication_methods}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))] diff --git a/crates/diesel_models/src/user_key_store.rs b/crates/diesel_models/src/user_key_store.rs index 1b19ef31a49..4d880ebf8f9 100644 --- a/crates/diesel_models/src/user_key_store.rs +++ b/crates/diesel_models/src/user_key_store.rs @@ -1,7 +1,8 @@ +use common_utils::encryption::Encryption; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, schema::user_key_store}; +use crate::schema::user_key_store; #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index ab569464684..310c2731b42 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true [features] default = ["olap", "payouts", "frm"] +encryption_service =[] olap = [] payouts = ["api_models/payouts"] frm = ["api_models/frm"] @@ -18,7 +19,7 @@ frm = ["api_models/frm"] api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } 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 = ["async_ext", "metrics"] } +common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext", "metrics", "encryption_service", "keymanager"] } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } masking = { version = "0.1.0", path = "../masking" } router_derive = { version = "0.1.0", path = "../router_derive" } @@ -31,6 +32,7 @@ error-stack = "0.4.1" futures = "0.3.30" http = "0.2.12" mime = "0.3.17" +rustc-hash = "1.1.0" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_with = "3.7.0" diff --git a/crates/hyperswitch_domain_models/src/behaviour.rs b/crates/hyperswitch_domain_models/src/behaviour.rs index 9976dd25a98..07911e8ea69 100644 --- a/crates/hyperswitch_domain_models/src/behaviour.rs +++ b/crates/hyperswitch_domain_models/src/behaviour.rs @@ -1,4 +1,7 @@ -use common_utils::errors::{CustomResult, ValidationError}; +use common_utils::{ + errors::{CustomResult, ValidationError}, + types::keymanager::KeyManagerState, +}; use masking::Secret; /// Trait for converting domain types to storage models @@ -9,8 +12,10 @@ pub trait Conversion { async fn convert(self) -> CustomResult<Self::DstType, ValidationError>; async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized; @@ -20,12 +25,22 @@ pub trait Conversion { #[async_trait::async_trait] pub trait ReverseConversion<SrcType: Conversion> { - async fn convert(self, key: &Secret<Vec<u8>>) -> CustomResult<SrcType, ValidationError>; + async fn convert( + self, + state: &KeyManagerState, + key: &Secret<Vec<u8>>, + key_store_ref_id: String, + ) -> CustomResult<SrcType, ValidationError>; } #[async_trait::async_trait] impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T { - async fn convert(self, key: &Secret<Vec<u8>>) -> CustomResult<U, ValidationError> { - U::convert_back(self, key).await + async fn convert( + self, + state: &KeyManagerState, + key: &Secret<Vec<u8>>, + key_store_ref_id: String, + ) -> CustomResult<U, ValidationError> { + U::convert_back(state, self, key, key_store_ref_id).await } } diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index e42f21dc7c7..a430673c59a 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -1,13 +1,14 @@ use common_utils::{ crypto::{OptionalEncryptableName, OptionalEncryptableValue}, date_time, + encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::ValueExt, pii, + types::keymanager, }; use diesel_models::{ - encryption::Encryption, enums::MerchantStorageScheme, - merchant_account::MerchantAccountUpdateInternal, + enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -195,8 +196,10 @@ impl super::behaviour::Conversion for MerchantAccount { } async fn convert_back( + state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, @@ -206,7 +209,7 @@ impl super::behaviour::Conversion for MerchantAccount { .ok_or(ValidationError::MissingRequiredField { field_name: "publishable_key".to_string(), })?; - + let identifier = keymanager::Identifier::Merchant(key_store_ref_id.clone()); async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { id: Some(item.id), @@ -217,11 +220,11 @@ impl super::behaviour::Conversion for MerchantAccount { redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item .merchant_name - .async_lift(|inner| decrypt(inner, key.peek())) + .async_lift(|inner| decrypt(state, inner, identifier.clone(), key.peek())) .await?, merchant_details: item .merchant_details - .async_lift(|inner| decrypt(inner, key.peek())) + .async_lift(|inner| decrypt(state, inner, identifier.clone(), key.peek())) .await?, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, diff --git a/crates/hyperswitch_domain_models/src/merchant_key_store.rs b/crates/hyperswitch_domain_models/src/merchant_key_store.rs index 29050b7eb49..76acf0f1404 100644 --- a/crates/hyperswitch_domain_models/src/merchant_key_store.rs +++ b/crates/hyperswitch_domain_models/src/merchant_key_store.rs @@ -2,6 +2,7 @@ use common_utils::{ crypto::{Encryptable, GcmAes256}, custom_serde, date_time, errors::{CustomResult, ValidationError}, + types::keymanager::{Identifier, KeyManagerState}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -30,14 +31,17 @@ impl super::behaviour::Conversion for MerchantKeyStore { } async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { + let identifier = Identifier::Merchant(item.merchant_id.clone()); Ok(Self { - key: Encryptable::decrypt(item.key, key.peek(), GcmAes256) + key: Encryptable::decrypt_via_api(state, item.key, identifier, key.peek(), GcmAes256) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 6ff74a95e46..5f8dd3934a2 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1,9 +1,10 @@ use api_models::enums::Connector; use common_enums as storage_enums; use common_utils::{ + encryption::Encryption, errors::{CustomResult, ValidationError}, pii, - types::MinorUnit, + types::{keymanager::KeyManagerState, MinorUnit}, }; use error_stack::ResultExt; use masking::PeekInterface; @@ -479,8 +480,7 @@ impl ForeignIDRef for PaymentAttempt { } use diesel_models::{ - encryption::Encryption, PaymentIntent as DieselPaymentIntent, - PaymentIntentNew as DieselPaymentIntentNew, + PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, }; #[async_trait::async_trait] @@ -542,14 +542,23 @@ impl behaviour::Conversion for PaymentIntent { } async fn convert_back( + state: &KeyManagerState, storage_model: Self::DstType, key: &masking::Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { - let inner_decrypt = |inner| decrypt(inner, key.peek()); + let inner_decrypt = |inner| { + decrypt( + state, + inner, + common_utils::types::keymanager::Identifier::Merchant(key_store_ref_id.clone()), + key.peek(), + ) + }; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 6eb35616729..f4f6be97055 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -2,9 +2,10 @@ use common_enums as storage_enums; use common_utils::{ consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, crypto::Encryptable, + encryption::Encryption, id_type, pii::{self, Email}, - types::MinorUnit, + types::{keymanager::KeyManagerState, MinorUnit}, }; use masking::{Deserialize, Secret}; use serde::Serialize; @@ -16,6 +17,7 @@ use crate::{errors, merchant_key_store::MerchantKeyStore, RemoteStorageObject}; pub trait PaymentIntentInterface { async fn update_payment_intent( &self, + state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, @@ -24,6 +26,7 @@ pub trait PaymentIntentInterface { async fn insert_payment_intent( &self, + state: &KeyManagerState, new: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, @@ -31,6 +34,7 @@ pub trait PaymentIntentInterface { async fn find_payment_intent_by_payment_id_merchant_id( &self, + state: &KeyManagerState, payment_id: &str, merchant_id: &str, merchant_key_store: &MerchantKeyStore, @@ -46,6 +50,7 @@ pub trait PaymentIntentInterface { #[cfg(feature = "olap")] async fn filter_payment_intent_by_constraints( &self, + state: &KeyManagerState, merchant_id: &str, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -55,6 +60,7 @@ pub trait PaymentIntentInterface { #[cfg(feature = "olap")] async fn filter_payment_intents_by_time_range_constraints( &self, + state: &KeyManagerState, merchant_id: &str, time_range: &api_models::payments::TimeRange, merchant_key_store: &MerchantKeyStore, @@ -64,6 +70,7 @@ pub trait PaymentIntentInterface { #[cfg(feature = "olap")] async fn get_filtered_payment_intents_attempt( &self, + state: &KeyManagerState, merchant_id: &str, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -467,7 +474,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { } use diesel_models::{ - encryption::Encryption, PaymentIntentUpdate as DieselPaymentIntentUpdate, + PaymentIntentUpdate as DieselPaymentIntentUpdate, PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields, }; diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs index 82d904ccf49..d656afc9251 100644 --- a/crates/hyperswitch_domain_models/src/type_encryption.rs +++ b/crates/hyperswitch_domain_models/src/type_encryption.rs @@ -1,14 +1,30 @@ use async_trait::async_trait; use common_utils::{ crypto, + encryption::Encryption, errors::{self, CustomResult}, ext_traits::AsyncExt, metrics::utils::record_operation_time, + types::keymanager::{Identifier, KeyManagerState}, }; -use diesel_models::encryption::Encryption; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; +use rustc_hash::FxHashMap; +#[cfg(feature = "encryption_service")] +use { + common_utils::{ + keymanager::call_encryption_service, + transformers::{ForeignFrom, ForeignTryFrom}, + types::keymanager::{ + BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse, + DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, + TransientBatchDecryptDataRequest, TransientDecryptDataRequest, + }, + }, + http::Method, + router_env::logger, +}; #[async_trait] pub trait TypeEncryption< @@ -17,6 +33,22 @@ pub trait TypeEncryption< S: masking::Strategy<T>, >: Sized { + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<T, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError>; + + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError>; + async fn encrypt( masked_data: Secret<T, S>, key: &[u8], @@ -28,31 +60,141 @@ pub trait TypeEncryption< key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; + + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<T, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<T, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<String> + Send, + S: masking::Strategy<String> + Send + Sync, > TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>> { #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<String, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + async fn encrypt( masked_data: Secret<String, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?; - Ok(Self::new(masked_data, encrypted_data.into())) } - #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; @@ -62,25 +204,227 @@ impl< Ok(Self::new(value.into(), encrypted)) } + + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<String, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<String, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new( + v.clone(), + crypt_algo.encode_message(key, v.peek().as_bytes())?.into(), + ), + )) + }) + .collect() + } + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + let data = crypt_algo.decode_message(key, v.clone().into_inner())?; + let value: String = std::str::from_utf8(&data) + .change_context(errors::CryptoError::DecodingFailed)? + .to_string(); + Ok((k, Self::new(value.into(), v.into_inner()))) + }) + .collect() + } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<serde_json::Value> + Send, + S: masking::Strategy<serde_json::Value> + Send + Sync, > TypeEncryption<serde_json::Value, V, S> for crypto::Encryptable<Secret<serde_json::Value, S>> { + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<serde_json::Value, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::EncodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + #[instrument(skip_all)] async fn encrypt( masked_data: Secret<serde_json::Value, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let data = serde_json::to_vec(&masked_data.peek()) .change_context(errors::CryptoError::DecodingFailed)?; let encrypted_data = crypt_algo.encode_message(key, &data)?; - Ok(Self::new(masked_data, encrypted_data.into())) } @@ -90,30 +434,229 @@ impl< key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; let value: serde_json::Value = serde_json::from_slice(&data).change_context(errors::CryptoError::DecodingFailed)?; - Ok(Self::new(value.into(), encrypted)) } + + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + let data = serde_json::to_vec(v.peek()) + .change_context(errors::CryptoError::DecodingFailed)?; + Ok(( + k, + Self::new(v, crypt_algo.encode_message(key, &data)?.into()), + )) + }) + .collect() + } + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + let data = crypt_algo.decode_message(key, v.clone().into_inner().clone())?; + + let value: serde_json::Value = serde_json::from_slice(&data) + .change_context(errors::CryptoError::DecodingFailed)?; + Ok((k, Self::new(value.into(), v.into_inner()))) + }) + .collect() + } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<Vec<u8>> + Send, + S: masking::Strategy<Vec<u8>> + Send + Sync, > TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>> { + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<Vec<u8>, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + #[instrument(skip_all)] async fn encrypt( masked_data: Secret<Vec<u8>, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?; - Ok(Self::new(masked_data, encrypted_data.into())) } @@ -123,11 +666,131 @@ impl< key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; - Ok(Self::new(data.into(), encrypted)) } + + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(response) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), response)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new(v.clone(), crypt_algo.encode_message(key, v.peek())?.into()), + )) + }) + .collect() + } + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new( + crypt_algo + .decode_message(key, v.clone().into_inner().clone())? + .into(), + v.into_inner(), + ), + )) + }) + .collect() + } } pub trait Lift<U> { @@ -178,7 +841,9 @@ impl<U, V: Lift<U> + Lift<U, SelfWrapper<U> = V> + Send> AsyncLift<U> for V { #[inline] pub async fn encrypt<E: Clone, S>( + state: &KeyManagerState, inner: Secret<E, S>, + identifier: Identifier, key: &[u8], ) -> CustomResult<crypto::Encryptable<Secret<E, S>>, errors::CryptoError> where @@ -186,7 +851,7 @@ where crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { record_operation_time( - crypto::Encryptable::encrypt(inner, key, crypto::GcmAes256), + crypto::Encryptable::encrypt_via_api(state, inner, identifier, key, crypto::GcmAes256), &metrics::ENCRYPTION_TIME, &metrics::CONTEXT, &[], @@ -194,9 +859,41 @@ where .await } +#[inline] +pub async fn batch_encrypt<E: Clone, S>( + state: &KeyManagerState, + inner: FxHashMap<String, Secret<E, S>>, + identifier: Identifier, + key: &[u8], +) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, errors::CryptoError> +where + S: masking::Strategy<E>, + crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, +{ + if !inner.is_empty() { + record_operation_time( + crypto::Encryptable::batch_encrypt_via_api( + state, + inner, + identifier, + key, + crypto::GcmAes256, + ), + &metrics::ENCRYPTION_TIME, + &metrics::CONTEXT, + &[], + ) + .await + } else { + Ok(FxHashMap::default()) + } +} + #[inline] pub async fn encrypt_optional<E: Clone, S>( + state: &KeyManagerState, inner: Option<Secret<E, S>>, + identifier: Identifier, key: &[u8], ) -> CustomResult<Option<crypto::Encryptable<Secret<E, S>>>, errors::CryptoError> where @@ -204,19 +901,26 @@ where S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { - inner.async_map(|f| encrypt(f, key)).await.transpose() + inner + .async_map(|f| encrypt(state, f, identifier, key)) + .await + .transpose() } #[inline] pub async fn decrypt<T: Clone, S: masking::Strategy<T>>( + state: &KeyManagerState, inner: Option<Encryption>, + identifier: Identifier, key: &[u8], ) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, errors::CryptoError> where crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { record_operation_time( - inner.async_map(|item| crypto::Encryptable::decrypt(item, key, crypto::GcmAes256)), + inner.async_map(|item| { + crypto::Encryptable::decrypt_via_api(state, item, identifier, key, crypto::GcmAes256) + }), &metrics::DECRYPTION_TIME, &metrics::CONTEXT, &[], @@ -225,8 +929,38 @@ where .transpose() } +#[inline] +pub async fn batch_decrypt<E: Clone, S>( + state: &KeyManagerState, + inner: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], +) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, errors::CryptoError> +where + S: masking::Strategy<E>, + crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, +{ + if !inner.is_empty() { + record_operation_time( + crypto::Encryptable::batch_decrypt_via_api( + state, + inner, + identifier, + key, + crypto::GcmAes256, + ), + &metrics::ENCRYPTION_TIME, + &metrics::CONTEXT, + &[], + ) + .await + } else { + Ok(FxHashMap::default()) + } +} + pub(crate) mod metrics { - use router_env::{global_meter, histogram_metric, metrics_context, once_cell}; + use router_env::{counter_metric, global_meter, histogram_metric, metrics_context, once_cell}; metrics_context!(CONTEXT); global_meter!(GLOBAL_METER, "ROUTER_API"); @@ -234,4 +968,8 @@ pub(crate) mod metrics { // Encryption and Decryption metrics histogram_metric!(ENCRYPTION_TIME, GLOBAL_METER); histogram_metric!(DECRYPTION_TIME, GLOBAL_METER); + counter_metric!(ENCRYPTION_API_FAILURES, GLOBAL_METER); + counter_metric!(DECRYPTION_API_FAILURES, GLOBAL_METER); + counter_metric!(APPLICATION_ENCRYPTION_COUNT, GLOBAL_METER); + counter_metric!(APPLICATION_DECRYPTION_COUNT, GLOBAL_METER); } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 1379b17eec4..b9488a0804e 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -11,12 +11,13 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls"] tls = ["actix-web/rustls-0_22"] -keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"] +keymanager_mtls = ["reqwest/rustls-tls","common_utils/keymanager_mtls"] +encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"] email = ["external_services/email", "scheduler/email", "olap"] keymanager_create = [] frm = ["api_models/frm", "hyperswitch_domain_models/frm"] stripe = ["dep:serde_qs"] -release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create"] +release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service"] olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] @@ -114,7 +115,7 @@ analytics = { version = "0.1.0", path = "../analytics", optional = true } api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } 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", "metrics", "keymanager"] } +common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 61f9c473a22..269c7d5b3b4 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -38,7 +38,11 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { let api_client = Box::new( services::ProxyClient::new( conf.proxy.clone(), - services::proxy_bypass_urls(&conf.locker, &conf.proxy.bypass_proxy_urls), + services::proxy_bypass_urls( + conf.key_manager.get_inner(), + &conf.locker, + &conf.proxy.bypass_proxy_urls, + ), ) .change_context(ProcessTrackerError::ConfigurationError)?, ); diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index d3091875f48..bdf8db2828e 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -2,6 +2,7 @@ pub mod opensearch; #[cfg(feature = "olap")] pub mod user; pub mod user_role; +use common_utils::consts; pub use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}; // ID generation pub(crate) const ID_LENGTH: usize = 20; @@ -43,8 +44,9 @@ pub(crate) const CANNOT_CONTINUE_AUTH: &str = pub(crate) const DEFAULT_NOTIFICATION_SCRIPT_LANGUAGE: &str = "en-US"; // General purpose base64 engines -pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = - base64::engine::general_purpose::STANDARD; + +pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = consts::BASE64_ENGINE; + pub(crate) const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 8a7854d658b..a851be95d5e 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -8,9 +8,8 @@ use common_utils::{ date_time, ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, id_type, pii, + types::keymanager as km_types, }; -#[cfg(all(feature = "keymanager_create", feature = "olap"))] -use common_utils::{keymanager, types::keymanager as km_types}; use diesel_models::configs; use error_stack::{report, FutureExt, ResultExt}; use futures::future::try_join_all; @@ -111,6 +110,9 @@ pub async fn create_merchant_account( state: SessionState, req: api::MerchantAccountCreate, ) -> RouterResponse<api::MerchantAccountResponse> { + #[cfg(feature = "keymanager_create")] + use common_utils::keymanager; + let db = state.store.as_ref(); let key = services::generate_aes256_key() @@ -119,27 +121,16 @@ pub async fn create_merchant_account( let master_key = db.get_master_key(); + let key_manager_state = &(&state).into(); let merchant_id = req.get_merchant_reference_id().get_string_repr().to_owned(); - - let key_store = domain::MerchantKeyStore { - merchant_id: merchant_id.clone(), - key: domain_types::encrypt(key.to_vec().into(), master_key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to decrypt data from key store")?, - created_at: date_time::now(), - }; - - let domain_merchant_account = req - .create_domain_model_from_request(db, key_store.clone()) - .await?; + let identifier = km_types::Identifier::Merchant(merchant_id.clone()); #[cfg(feature = "keymanager_create")] { keymanager::create_key_in_key_manager( - &(&state).into(), + key_manager_state, km_types::EncryptionCreateRequest { - identifier: km_types::Identifier::Merchant(merchant_id.clone()), + identifier: identifier.clone(), }, ) .await @@ -147,12 +138,34 @@ pub async fn create_merchant_account( .attach_printable("Failed to insert key to KeyManager")?; } - db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into()) + let key_store = domain::MerchantKeyStore { + merchant_id: merchant_id.clone(), + key: domain_types::encrypt( + key_manager_state, + key.to_vec().into(), + identifier.clone(), + master_key, + ) .await - .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to decrypt data from key store")?, + created_at: date_time::now(), + }; + + let domain_merchant_account = req + .create_domain_model_from_request(&state, key_store.clone()) + .await?; + let key_manager_state = &(&state).into(); + db.insert_merchant_key_store( + key_manager_state, + key_store.clone(), + &master_key.to_vec().into(), + ) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; let merchant_account = db - .insert_merchant(domain_merchant_account, &key_store) + .insert_merchant(key_manager_state, domain_merchant_account, &key_store) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; @@ -172,7 +185,7 @@ pub async fn create_merchant_account( trait MerchantAccountCreateBridge { async fn create_domain_model_from_request( self, - db: &dyn StorageInterface, + state: &SessionState, key: domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount>; } @@ -182,9 +195,10 @@ trait MerchantAccountCreateBridge { impl MerchantAccountCreateBridge for api::MerchantAccountCreate { async fn create_domain_model_from_request( self, - db: &dyn StorageInterface, + state: &SessionState, key_store: domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount> { + let db = &*state.store; let publishable_key = create_merchant_publishable_key(); let primary_business_details = self.get_primary_details_as_value().change_context( @@ -229,7 +243,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { let payment_response_hash_key = self.get_payment_response_hash_key(); let parent_merchant_id = get_parent_merchant( - db, + state, self.sub_merchants_enabled, self.parent_merchant_id, &key_store, @@ -241,6 +255,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .await?; let key = key_store.key.clone().into_inner(); + let key_manager_state = state.into(); let mut merchant_account = async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( @@ -248,10 +263,24 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { merchant_id: self.merchant_id.get_string_repr().to_owned(), merchant_name: self .merchant_name - .async_lift(|inner| domain_types::encrypt_optional(inner, key.peek())) + .async_lift(|inner| { + domain_types::encrypt_optional( + &key_manager_state, + inner, + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key.peek(), + ) + }) .await?, merchant_details: merchant_details - .async_lift(|inner| domain_types::encrypt_optional(inner, key.peek())) + .async_lift(|inner| { + domain_types::encrypt_optional( + &key_manager_state, + inner, + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key.peek(), + ) + }) .await?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, @@ -293,7 +322,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .change_context(errors::ApiErrorResponse::InternalServerError)?; CreateBusinessProfile::new(self.primary_business_details.clone()) - .create_business_profiles(db, &mut merchant_account, &key_store) + .create_business_profiles(state, &mut merchant_account, &key_store) .await?; Ok(merchant_account) @@ -385,7 +414,7 @@ impl CreateBusinessProfile { async fn create_business_profiles( &self, - db: &dyn StorageInterface, + state: &SessionState, merchant_account: &mut domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { @@ -394,7 +423,7 @@ impl CreateBusinessProfile { primary_business_details, } => { let business_profiles = Self::create_business_profiles_for_each_business_details( - db, + state, merchant_account.clone(), primary_business_details, key_store, @@ -410,7 +439,7 @@ impl CreateBusinessProfile { } Self::CreateDefaultBusinessProfile => { let business_profile = self - .create_default_business_profile(db, merchant_account.clone(), key_store) + .create_default_business_profile(state, merchant_account.clone(), key_store) .await?; merchant_account.default_profile = Some(business_profile.profile_id); @@ -423,12 +452,12 @@ impl CreateBusinessProfile { /// Create default business profile async fn create_default_business_profile( &self, - db: &dyn StorageInterface, + state: &SessionState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<diesel_models::business_profile::BusinessProfile> { let business_profile = create_and_insert_business_profile( - db, + state, api_models::admin::BusinessProfileCreate::default(), merchant_account.clone(), key_store, @@ -442,7 +471,7 @@ impl CreateBusinessProfile { /// If there is no default profile in merchant account and only one primary_business_detail /// is available, then create a default business profile. async fn create_business_profiles_for_each_business_details( - db: &dyn StorageInterface, + state: &SessionState, merchant_account: domain::MerchantAccount, primary_business_details: &Vec<admin_types::PrimaryBusinessDetails>, key_store: &domain::MerchantKeyStore, @@ -462,7 +491,7 @@ impl CreateBusinessProfile { }; create_and_insert_business_profile( - db, + state, business_profile_create_request, merchant_account.clone(), key_store, @@ -486,10 +515,11 @@ impl CreateBusinessProfile { impl MerchantAccountCreateBridge for api::MerchantAccountCreate { async fn create_domain_model_from_request( self, - db: &dyn StorageInterface, + state: &SessionState, key_store: domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount> { let publishable_key = create_merchant_publishable_key(); + let db = &*state.store; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { @@ -514,24 +544,36 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .await?; let key = key_store.key.into_inner(); + let merchant_id = self + .get_merchant_reference_id() + .get_string_repr() + .to_owned(); + let key_manager_state = state.into(); + let identifier = km_types::Identifier::Merchant(merchant_id.clone()); async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccount { - merchant_id: self - .get_merchant_reference_id() - .get_string_repr() - .to_owned(), + merchant_id, merchant_name: Some( domain_types::encrypt( + &key_manager_state, self.merchant_name .map(|merchant_name| merchant_name.into_inner()), + identifier.clone(), key.peek(), ) .await?, ), merchant_details: merchant_details - .async_lift(|inner| domain_types::encrypt_optional(inner, key.peek())) + .async_lift(|inner| { + domain_types::encrypt_optional( + &key_manager_state, + inner, + identifier.clone(), + key.peek(), + ) + }) .await?, return_url: None, webhook_details: None, @@ -577,7 +619,7 @@ pub async fn list_merchant_account( ) -> RouterResponse<Vec<api::MerchantAccountResponse>> { let merchant_accounts = state .store - .list_merchant_accounts_by_organization_id(&req.organization_id) + .list_merchant_accounts_by_organization_id(&(&state).into(), &req.organization_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -600,8 +642,10 @@ pub async fn get_merchant_account( req: api::MerchantId, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, &req.merchant_id, &db.get_master_key().to_vec().into(), ) @@ -609,7 +653,7 @@ pub async fn get_merchant_account( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db - .find_merchant_account_by_merchant_id(&req.merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -623,13 +667,15 @@ pub async fn get_merchant_account( /// For backwards compatibility, whenever new business labels are passed in /// primary_business_details, create a business profile pub async fn create_business_profile_from_business_labels( + state: &SessionState, db: &dyn StorageInterface, key_store: &domain::MerchantKeyStore, merchant_id: &str, new_business_details: Vec<admin_types::PrimaryBusinessDetails>, ) -> RouterResult<()> { + let key_manager_state = &state.into(); let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -657,7 +703,7 @@ pub async fn create_business_profile_from_business_labels( }; let business_profile_create_result = create_and_insert_business_profile( - db, + state, business_profile_create_request, merchant_account.clone(), key_store, @@ -673,9 +719,14 @@ pub async fn create_business_profile_from_business_labels( // If a business_profile is created, then unset the default profile if business_profile_create_result.is_ok() && merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; - db.update_merchant(merchant_account.clone(), unset_default_profile, key_store) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + db.update_merchant( + key_manager_state, + merchant_account.clone(), + unset_default_profile, + key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } } @@ -758,8 +809,10 @@ pub async fn merchant_account_update( req: api::MerchantAccountUpdate, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, &req.merchant_id, &db.get_master_key().to_vec().into(), ) @@ -817,6 +870,7 @@ pub async fn merchant_account_update( .clone() .async_map(|primary_business_details| async { let _ = create_business_profile_from_business_labels( + &state, db, &key_store, merchant_id, @@ -845,11 +899,14 @@ pub async fn merchant_account_update( // Update the business profile, This is for backwards compatibility update_business_profile_cascade(state.clone(), req.clone(), merchant_id.to_string()).await?; + let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); let updated_merchant_account = storage::MerchantAccountUpdate::Update { merchant_name: req .merchant_name .map(Secret::new) - .async_lift(|inner| domain_types::encrypt_optional(inner, key)) + .async_lift(|inner| { + domain_types::encrypt_optional(key_manager_state, inner, identifier.clone(), key) + }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant name")?, @@ -862,7 +919,9 @@ pub async fn merchant_account_update( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to convert merchant_details to a value")? .map(Secret::new) - .async_lift(|inner| domain_types::encrypt_optional(inner, key)) + .async_lift(|inner| { + domain_types::encrypt_optional(key_manager_state, inner, identifier.clone(), key) + }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant details")?, @@ -880,7 +939,7 @@ pub async fn merchant_account_update( sub_merchants_enabled: req.sub_merchants_enabled, parent_merchant_id: get_parent_merchant( - db, + &state, req.sub_merchants_enabled, req.parent_merchant_id, &key_store, @@ -905,7 +964,12 @@ pub async fn merchant_account_update( }; let response = db - .update_specific_fields_in_merchant(merchant_id, updated_merchant_account, &key_store) + .update_specific_fields_in_merchant( + key_manager_state, + merchant_id, + updated_merchant_account, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -924,9 +988,10 @@ pub async fn merchant_account_delete( ) -> RouterResponse<api::MerchantAccountDeleteResponse> { let mut is_deleted = false; let db = state.store.as_ref(); - + let key_manager_state = &(&state).into(); let merchant_key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -934,7 +999,7 @@ pub async fn merchant_account_delete( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &merchant_key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &merchant_key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -988,7 +1053,7 @@ pub async fn merchant_account_delete( } async fn get_parent_merchant( - db: &dyn StorageInterface, + state: &SessionState, sub_merchants_enabled: Option<bool>, parent_merchant: Option<String>, key_store: &domain::MerchantKeyStore, @@ -1004,7 +1069,7 @@ async fn get_parent_merchant( message: "If `sub_merchants_enabled` is `true`, then `parent_merchant_id` is mandatory".to_string(), }) }) - .map(|id| validate_merchant_id(db, id,key_store).change_context( + .map(|id| validate_merchant_id(state, id,key_store).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "parent_merchant_id" } ))? .await? @@ -1016,11 +1081,12 @@ async fn get_parent_merchant( } async fn validate_merchant_id<S: Into<String>>( - db: &dyn StorageInterface, + state: &SessionState, merchant_id: S, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount> { - db.find_merchant_account_by_merchant_id(&merchant_id.into(), key_store) + let db = &*state.store; + db.find_merchant_account_by_merchant_id(&state.into(), &merchant_id.into(), key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) } @@ -1066,10 +1132,12 @@ pub async fn create_payment_connector( merchant_id: &String, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); + let key_manager_state = &(&state).into(); #[cfg(feature = "dummy_connector")] validate_dummy_connector_enabled(&state, &req.connector_name).await?; let key_store = store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -1083,7 +1151,7 @@ pub async fn create_payment_connector( let merchant_account = state .store - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1221,6 +1289,7 @@ pub async fn create_payment_connector( state .store .update_specific_fields_in_merchant( + key_manager_state, merchant_id, storage::MerchantAccountUpdate::ModifiedAtUpdate, &key_store, @@ -1242,7 +1311,7 @@ pub async fn create_payment_connector( if let Some(val) = req.pm_auth_config.clone() { validate_pm_auth( val, - &*state.clone().store, + &state, merchant_id.clone().as_str(), &key_store, merchant_account, @@ -1256,14 +1325,15 @@ pub async fn create_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encoding ConnectorAuthType to serde_json::Value")?; let conn_auth = Secret::new(connector_auth); - + let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type, connector_name: req.connector_name.to_string(), merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"), - connector_account_details: domain_types::encrypt( + connector_account_details: domain_types::encrypt(key_manager_state, conn_auth, + identifier.clone(), key_store.key.peek(), ) .await @@ -1296,10 +1366,11 @@ pub async fn create_payment_connector( applepay_verified_domains: None, pm_auth_config: req.pm_auth_config.clone(), status: connector_status, - connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(&key_store, &req.metadata).await?, + connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(&state, &key_store, &req.metadata).await?, additional_merchant_data: if let Some(mcd) = merchant_recipient_data { - Some(domain_types::encrypt( + Some(domain_types::encrypt(key_manager_state, Secret::new(mcd), + identifier, key_store.key.peek(), ) .await @@ -1329,7 +1400,11 @@ pub async fn create_payment_connector( let mca = state .store - .insert_merchant_connector_account(merchant_connector_account, &key_store) + .insert_merchant_connector_account( + key_manager_state, + merchant_connector_account, + &key_store, + ) .await .to_duplicate_response( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { @@ -1382,7 +1457,7 @@ pub async fn create_payment_connector( async fn validate_pm_auth( val: serde_json::Value, - db: &dyn StorageInterface, + state: &SessionState, merchant_id: &str, key_store: &domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, @@ -1394,8 +1469,10 @@ async fn validate_pm_auth( }) .attach_printable("Failed to deserialize Payment Method Auth config")?; - let all_mcas = db + let all_mcas = &*state + .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_id, true, key_store, @@ -1407,8 +1484,7 @@ async fn validate_pm_auth( for conn_choice in config.enabled_payment_methods { let pm_auth_mca = all_mcas - .clone() - .into_iter() + .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(), @@ -1432,8 +1508,10 @@ pub async fn retrieve_payment_connector( merchant_connector_id: String, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) @@ -1441,12 +1519,13 @@ pub async fn retrieve_payment_connector( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = store - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_id, &merchant_connector_id, &key_store, @@ -1464,8 +1543,10 @@ pub async fn list_payment_connectors( merchant_id: String, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorResponse>> { let store = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) @@ -1474,12 +1555,13 @@ pub async fn list_payment_connectors( // Validate merchant account store - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_connector_accounts = store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, &merchant_id, true, &key_store, @@ -1503,18 +1585,24 @@ pub async fn update_payment_connector( req: api_models::admin::MerchantConnectorUpdate, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + 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) + .find_merchant_account_by_merchant_id(key_manager_state, 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( + key_manager_state, merchant_id, merchant_connector_id, &key_store, @@ -1559,7 +1647,7 @@ pub async fn update_payment_connector( if let Some(val) = req.pm_auth_config.clone() { validate_pm_auth( val, - db, + &state, merchant_id, &key_store, merchant_account, @@ -1568,7 +1656,6 @@ pub async fn update_payment_connector( .await?; } } - let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: None, connector_type: Some(req.connector_type), @@ -1578,7 +1665,12 @@ pub async fn update_payment_connector( connector_account_details: req .connector_account_details .async_lift(|inner| { - domain_types::encrypt_optional(inner, key_store.key.get_inner().peek()) + domain_types::encrypt_optional( + key_manager_state, + inner, + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key_store.key.get_inner().peek(), + ) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1600,7 +1692,7 @@ pub async fn update_payment_connector( pm_auth_config: req.pm_auth_config, status: Some(connector_status), connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details( - &key_store, &metadata, + &state, &key_store, &metadata, ) .await?, }; @@ -1615,7 +1707,12 @@ pub async fn update_payment_connector( let request_connector_label = req.connector_label; let updated_mca = db - .update_merchant_connector_account(mca, payment_connector.into(), &key_store) + .update_merchant_connector_account( + key_manager_state, + mca, + payment_connector.into(), + &key_store, + ) .await .change_context( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { @@ -1638,18 +1735,24 @@ pub async fn delete_payment_connector( merchant_connector_id: String, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &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) + .find_merchant_account_by_merchant_id(key_manager_state, &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( + key_manager_state, &merchant_id, &merchant_connector_id, &key_store, @@ -1683,14 +1786,19 @@ pub async fn kv_for_merchant( enable: bool, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1707,6 +1815,7 @@ pub async fn kv_for_merchant( } db.update_merchant( + key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::RedisKv, @@ -1717,6 +1826,7 @@ pub async fn kv_for_merchant( } (false, MerchantStorageScheme::RedisKv) => { db.update_merchant( + key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::PostgresOnly, @@ -1779,14 +1889,19 @@ pub async fn check_merchant_account_kv_status( merchant_id: String, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1825,17 +1940,19 @@ pub fn get_frm_config_as_secret( } pub async fn create_and_insert_business_profile( - db: &dyn StorageInterface, + state: &SessionState, request: api::BusinessProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::business_profile::BusinessProfile> { let business_profile_new = - admin::create_business_profile(merchant_account, request, key_store).await?; + admin::create_business_profile(state, merchant_account, request, key_store).await?; let profile_name = business_profile_new.profile_name.clone(); - db.insert_business_profile(business_profile_new) + state + .store + .insert_business_profile(business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( @@ -1859,15 +1976,20 @@ pub async fn create_business_profile( } let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // Get the merchant account, if few fields are not passed, then they will be inherited from // merchant account let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1882,18 +2004,23 @@ pub async fn create_business_profile( } let business_profile = - create_and_insert_business_profile(db, request, merchant_account.clone(), &key_store) + create_and_insert_business_profile(&state, request, merchant_account.clone(), &key_store) .await?; if merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; - db.update_merchant(merchant_account, unset_default_profile, &key_store) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + db.update_merchant( + key_manager_state, + merchant_account, + unset_default_profile, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } Ok(service_api::ApplicationResponse::Json( - admin::business_profile_response(business_profile, &key_store) + admin::business_profile_response(&state, business_profile, &key_store) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details") .await?, @@ -1906,7 +2033,11 @@ pub async fn list_business_profile( ) -> RouterResponse<Vec<api_models::admin::BusinessProfileResponse>> { let db = state.store.as_ref(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + &(&state).into(), + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let profiles = db @@ -1916,7 +2047,7 @@ pub async fn list_business_profile( .clone(); let mut business_profiles = Vec::new(); for profile in profiles { - let business_profile = admin::business_profile_response(profile, &key_store) + let business_profile = admin::business_profile_response(&state, profile, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?; @@ -1933,7 +2064,11 @@ pub async fn retrieve_business_profile( ) -> RouterResponse<api_models::admin::BusinessProfileResponse> { let db = state.store.as_ref(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + &(&state).into(), + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let business_profile = db @@ -1944,7 +2079,7 @@ pub async fn retrieve_business_profile( })?; Ok(service_api::ApplicationResponse::Json( - admin::business_profile_response(business_profile, &key_store) + admin::business_profile_response(&state, business_profile, &key_store) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details") .await?, @@ -1982,6 +2117,7 @@ pub async fn update_business_profile( })?; let key_store = db .get_merchant_key_store_by_merchant_id( + &(&state).into(), merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -2051,7 +2187,7 @@ pub async fn update_business_profile( .map(Secret::new); let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers - .async_map(|headers| create_encrypted_data(&key_store, headers)) + .async_map(|headers| create_encrypted_data(&state, &key_store, headers)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2119,7 +2255,7 @@ pub async fn update_business_profile( })?; Ok(service_api::ApplicationResponse::Json( - admin::business_profile_response(updated_business_profile, &key_store) + admin::business_profile_response(&state, updated_business_profile, &key_store) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details") .await?, diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index df8a55cd718..6af82a6b7a8 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -122,6 +122,7 @@ pub async fn create_api_key( // non-existence of a merchant account. store .get_merchant_key_store_by_merchant_id( + &(&state).into(), merchant_id.as_str(), &store.get_master_key().to_vec().into(), ) diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rs index 327358bda50..87c15935715 100644 --- a/crates/router/src/core/apple_pay_certificates_migration.rs +++ b/crates/router/src/core/apple_pay_certificates_migration.rs @@ -1,5 +1,5 @@ use api_models::apple_pay_certificates_migration; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, types::keymanager::Identifier}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -28,11 +28,12 @@ pub async fn apple_pay_certificates_migration( let mut migration_successful_merchant_ids = vec![]; let mut migration_failed_merchant_ids = vec![]; - + let key_manager_state = &(&state).into(); for merchant_id in merchant_id_list { let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -41,6 +42,7 @@ pub async fn apple_pay_certificates_migration( let merchant_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, merchant_id, true, &key_store, @@ -63,11 +65,13 @@ pub async fn apple_pay_certificates_migration( .ok(); if let Some(apple_pay_metadata) = connector_apple_pay_metadata { let encrypted_apple_pay_metadata = domain_types::encrypt( + &(&state).into(), Secret::new( serde_json::to_value(apple_pay_metadata) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize apple pay metadata as JSON")?, ), + Identifier::Merchant(merchant_id.clone()), key_store.key.get_inner().peek(), ) .await diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs index 97324effa80..c739a86ee51 100644 --- a/crates/router/src/core/blocklist/utils.rs +++ b/crates/router/src/core/blocklist/utils.rs @@ -398,6 +398,7 @@ where if should_payment_be_blocked { // Update db for attempt and intent status. db.update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::RejectUpdate { status: common_enums::IntentStatus::Failed, diff --git a/crates/router/src/core/cards_info.rs b/crates/router/src/core/cards_info.rs index b0c1aca5322..98719b5a1e6 100644 --- a/crates/router/src/core/cards_info.rs +++ b/crates/router/src/core/cards_info.rs @@ -30,7 +30,7 @@ pub async fn retrieve_card_info( verify_iin_length(&request.card_iin)?; helpers::verify_payment_intent_time_and_client_secret( - db, + &state, &merchant_account, &key_store, request.client_secret, diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rs index f740c6dfcc2..c34f8e7116d 100644 --- a/crates/router/src/core/conditional_config.rs +++ b/crates/router/src/core/conditional_config.rs @@ -102,7 +102,7 @@ pub async fn upsert_conditional_config( algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -138,7 +138,7 @@ pub async fn upsert_conditional_config( algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -168,7 +168,7 @@ pub async fn delete_conditional_config( .unwrap_or_default(); algo_id.config_algo_id = None; let config_key = cache::CacheKind::DecisionManager(key.clone().into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index c0e0291b8c4..e9126200acc 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -1,10 +1,12 @@ +use api_models::customers::CustomerRequestWithEmail; use common_utils::{ crypto::{Encryptable, GcmAes256}, errors::ReportSwitchExt, ext_traits::OptionExt, + types::keymanager::{Identifier, ToEncryptable}, }; use error_stack::{report, ResultExt}; -use masking::ExposeInterface; +use masking::{Secret, SwitchStrategy}; use router_env::{instrument, tracing}; use crate::{ @@ -19,7 +21,7 @@ use crate::{ api::customers, domain::{ self, - types::{self, AsyncLift, TypeEncryption}, + types::{self, TypeEncryption}, }, storage::{self, enums}, }, @@ -43,6 +45,7 @@ pub async fn create_customer( let merchant_id = &merchant_account.merchant_id; merchant_id.clone_into(&mut customer_data.merchant_id); + let key_manager_state = &(&state).into(); // We first need to validate whether the customer with the given customer id already exists // this may seem like a redundant db call, as the insert_customer will anyway return this error @@ -51,6 +54,7 @@ pub async fn create_customer( // it errors out, now the address that was inserted is not deleted match db .find_customer_by_customer_id_merchant_id( + key_manager_state, &customer_id, merchant_id, &key_store, @@ -76,6 +80,7 @@ pub async fn create_customer( let address = customer_data .get_domain_address( + &state, customer_address, merchant_id, &customer_id, @@ -87,7 +92,7 @@ pub async fn create_customer( .attach_printable("Failed while encrypting address")?; Some( - db.insert_address_for_customers(address, &key_store) + db.insert_address_for_customers(key_manager_state, address, &key_store) .await .switch() .attach_printable("Failed while inserting new address")?, @@ -96,40 +101,46 @@ pub async fn create_customer( None }; - let new_customer = async { - Ok(domain::Customer { - customer_id: customer_id.to_owned(), - merchant_id: merchant_id.to_string(), - name: customer_data - .name - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - email: customer_data - .email - .async_lift(|inner| types::encrypt_optional(inner.map(|inner| inner.expose()), key)) - .await?, - phone: customer_data - .phone - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - description: customer_data.description, - phone_country_code: customer_data.phone_country_code, - metadata: customer_data.metadata, - id: None, - connector_customer: None, - address_id: address.clone().map(|addr| addr.address_id), - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), - default_payment_method_id: None, - updated_by: None, - }) - } + let encrypted_data = types::batch_encrypt( + &(&state).into(), + CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail { + name: customer_data.name.clone(), + email: customer_data.email.clone(), + phone: customer_data.phone.clone(), + }), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) .await .switch() .attach_printable("Failed while encrypting Customer")?; + let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) + .change_context(errors::CustomersErrorResponse::InternalServerError)?; + let new_customer = domain::Customer { + customer_id: customer_id.to_owned(), + merchant_id: merchant_id.to_string(), + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: encryptable_customer.phone, + description: customer_data.description, + phone_country_code: customer_data.phone_country_code, + metadata: customer_data.metadata, + id: None, + connector_customer: None, + address_id: address.clone().map(|addr| addr.address_id), + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + default_payment_method_id: None, + updated_by: None, + }; let customer = db - .insert_customer(new_customer, &key_store, merchant_account.storage_scheme) + .insert_customer( + key_manager_state, + new_customer, + &key_store, + merchant_account.storage_scheme, + ) .await .to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?; @@ -148,8 +159,10 @@ pub async fn retrieve_customer( req: customers::CustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let response = db .find_customer_by_customer_id_merchant_id( + key_manager_state, &req.customer_id, &merchant_account.merchant_id, &key_store, @@ -159,7 +172,7 @@ pub async fn retrieve_customer( .switch()?; let address = match &response.address_id { Some(address_id) => Some(api_models::payments::AddressDetails::from( - db.find_address_by_address_id(address_id, &key_store) + db.find_address_by_address_id(key_manager_state, address_id, &key_store) .await .switch()?, )), @@ -179,7 +192,7 @@ pub async fn list_customers( let db = state.store.as_ref(); let domain_customers = db - .list_customers_by_merchant_id(&merchant_id, &key_store) + .list_customers_by_merchant_id(&(&state).into(), &merchant_id, &key_store) .await .switch()?; @@ -199,9 +212,10 @@ pub async fn delete_customer( key_store: domain::MerchantKeyStore, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &state.store; - + let key_manager_state = &(&state).into(); let customer_orig = db .find_customer_by_customer_id_merchant_id( + key_manager_state, &req.customer_id, &merchant_account.merchant_id, &key_store, @@ -262,17 +276,24 @@ pub async fn delete_customer( }; let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let redacted_encrypted_value: Encryptable<Secret<_>> = Encryptable::encrypt_via_api( + key_manager_state, + REDACTED.to_string().into(), + identifier.clone(), + key, + GcmAes256, + ) + .await + .switch()?; - let redacted_encrypted_value: Encryptable<masking::Secret<_>> = - Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) - .await - .switch()?; - - let redacted_encrypted_email: Encryptable< - masking::Secret<_, common_utils::pii::EmailStrategy>, - > = Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) - .await - .switch()?; + let redacted_encrypted_email = Encryptable::new( + redacted_encrypted_value + .clone() + .into_inner() + .switch_strategy(), + redacted_encrypted_value.clone().into_encrypted(), + ); let update_address = storage::AddressUpdate::Update { city: Some(REDACTED.to_string()), @@ -292,6 +313,7 @@ pub async fn delete_customer( match db .update_address_by_merchant_id_customer_id( + key_manager_state, &req.customer_id, &merchant_account.merchant_id, update_address, @@ -314,9 +336,15 @@ pub async fn delete_customer( let updated_customer = storage::CustomerUpdate::Update { name: Some(redacted_encrypted_value.clone()), email: Some( - Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) - .await - .switch()?, + Encryptable::encrypt_via_api( + key_manager_state, + REDACTED.to_string().into(), + identifier, + key, + GcmAes256, + ) + .await + .switch()?, ), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(REDACTED.to_string()), @@ -326,6 +354,7 @@ pub async fn delete_customer( address_id: None, }; db.update_customer_by_customer_id_merchant_id( + key_manager_state, req.customer_id.clone(), merchant_account.merchant_id, customer_orig, @@ -362,9 +391,10 @@ pub async fn update_customer( .get_required_value("customer_id") .change_context(errors::CustomersErrorResponse::InternalServerError) .attach("Missing required field `customer_id`")?; - + let key_manager_state = &(&state).into(); let customer = db .find_customer_by_customer_id_merchant_id( + key_manager_state, customer_id, &merchant_account.merchant_id, &key_store, @@ -380,12 +410,18 @@ pub async fn update_customer( Some(address_id) => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let update_address = update_customer - .get_address_update(customer_address, key, merchant_account.storage_scheme) + .get_address_update( + &state, + customer_address, + key, + merchant_account.storage_scheme, + merchant_account.merchant_id.clone(), + ) .await .switch() .attach_printable("Failed while encrypting Address while Update")?; Some( - db.update_address(address_id, update_address, &key_store) + db.update_address(key_manager_state, address_id, update_address, &key_store) .await .switch() .attach_printable(format!( @@ -399,6 +435,7 @@ pub async fn update_customer( let address = update_customer .get_domain_address( + &state, customer_address, &merchant_account.merchant_id, &customer.customer_id, @@ -409,7 +446,7 @@ pub async fn update_customer( .switch() .attach_printable("Failed while encrypting address")?; Some( - db.insert_address_for_customers(address, &key_store) + db.insert_address_for_customers(key_manager_state, address, &key_store) .await .switch() .attach_printable("Failed while inserting new address")?, @@ -419,47 +456,44 @@ pub async fn update_customer( } else { match &customer.address_id { Some(address_id) => Some( - db.find_address_by_address_id(address_id, &key_store) + db.find_address_by_address_id(key_manager_state, address_id, &key_store) .await .switch()?, ), None => None, } }; + let encrypted_data = types::batch_encrypt( + &(&state).into(), + CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail { + name: update_customer.name.clone(), + email: update_customer.email.clone(), + phone: update_customer.phone.clone(), + }), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + .await + .switch()?; + let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) + .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_customer_id_merchant_id( + key_manager_state, customer_id.to_owned(), merchant_account.merchant_id.to_owned(), customer, - async { - Ok(storage::CustomerUpdate::Update { - name: update_customer - .name - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - email: update_customer - .email - .async_lift(|inner| { - types::encrypt_optional(inner.map(|inner| inner.expose()), key) - }) - .await?, - phone: Box::new( - update_customer - .phone - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - ), - phone_country_code: update_customer.phone_country_code, - metadata: update_customer.metadata, - description: update_customer.description, - connector_customer: None, - address_id: address.clone().map(|addr| addr.address_id), - }) - } - .await - .switch() - .attach_printable("Failed while encrypting while updating customer")?, + storage::CustomerUpdate::Update { + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: Box::new(encryptable_customer.phone), + phone_country_code: update_customer.phone_country_code, + metadata: update_customer.metadata, + description: update_customer.description, + connector_customer: None, + address_id: address.clone().map(|addr| addr.address_id), + }, &key_store, merchant_account.storage_scheme, ) diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs index 2d2d7bbcaeb..6a7f531f5a0 100644 --- a/crates/router/src/core/disputes.rs +++ b/crates/router/src/core/disputes.rs @@ -89,6 +89,7 @@ pub async fn accept_dispute( )?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &dispute.payment_id, &merchant_account.merchant_id, &key_store, @@ -202,6 +203,7 @@ pub async fn submit_evidence( .await?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &dispute.payment_id, &merchant_account.merchant_id, &key_store, diff --git a/crates/router/src/core/encryption.rs b/crates/router/src/core/encryption.rs index 7f7945bfd1c..efd7d3bfeaa 100644 --- a/crates/router/src/core/encryption.rs +++ b/crates/router/src/core/encryption.rs @@ -14,7 +14,7 @@ pub async fn transfer_encryption_key( ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let db = &*state.store; let key_stores = db - .get_all_key_stores(&db.get_master_key().to_vec().into()) + .get_all_key_stores(&state.into(), &db.get_master_key().to_vec().into()) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; send_request_to_key_service_for_merchant(state, key_stores).await diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 3a565865603..ed95e7790e7 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -261,6 +261,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &dispute.payment_id, &merchant_account.merchant_id, key_store, diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 331eb430211..8ddd0b7aa24 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -123,7 +123,7 @@ where pub async fn should_call_frm<F>( merchant_account: &domain::MerchantAccount, payment_data: &payments::PaymentData<F>, - db: &dyn StorageInterface, + state: &SessionState, key_store: domain::MerchantKeyStore, ) -> RouterResult<( bool, @@ -136,6 +136,7 @@ where { match merchant_account.frm_routing_algorithm.clone() { Some(frm_routing_algorithm_value) => { + let db = &*state.store; let frm_routing_algorithm_struct: FrmRoutingAlgorithm = frm_routing_algorithm_value .clone() .parse_value("FrmRoutingAlgorithm") @@ -157,6 +158,7 @@ where let merchant_connector_account_from_db_option = db .find_merchant_connector_account_by_profile_id_connector_name( + &state.into(), &profile_id, &frm_routing_algorithm_struct.data, &key_store, @@ -417,7 +419,7 @@ where let frm_data_updated = fraud_check_operation .to_update_tracker()? .update_tracker( - &*state.store, + state, &key_store, frm_data.clone(), payment_data, @@ -492,7 +494,7 @@ where let mut frm_data = fraud_check_operation .to_update_tracker()? .update_tracker( - &*state.store, + state, &key_store, frm_data.to_owned(), payment_data, @@ -527,7 +529,7 @@ where let updated_frm_data = fraud_check_operation .to_update_tracker()? .update_tracker( - &*state.store, + state, &key_store, frm_data.to_owned(), payment_data, @@ -547,7 +549,6 @@ where #[allow(clippy::too_many_arguments)] pub async fn call_frm_before_connector_call<'a, F, Req>( - db: &dyn StorageInterface, operation: &BoxedOperation<'_, F, Req>, merchant_account: &domain::MerchantAccount, payment_data: &mut payments::PaymentData<F>, @@ -562,13 +563,13 @@ where F: Send + Clone, { let (is_frm_enabled, frm_routing_algorithm, frm_connector_label, frm_configs) = - should_call_frm(merchant_account, payment_data, db, key_store.clone()).await?; + should_call_frm(merchant_account, payment_data, state, key_store.clone()).await?; if let Some((frm_routing_algorithm_val, profile_id)) = frm_routing_algorithm.zip(frm_connector_label) { if let Some(frm_configs) = frm_configs.clone() { let mut updated_frm_info = Box::pin(make_frm_data_and_fraud_check_operation( - db, + &*state.store, state, merchant_account, payment_data.to_owned(), @@ -655,6 +656,7 @@ pub async fn frm_fulfillment_core( let db = &*state.clone().store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &req.payment_id.clone(), &merchant_account.merchant_id, &key_store, diff --git a/crates/router/src/core/fraud_check/operation.rs b/crates/router/src/core/fraud_check/operation.rs index 8c6f8b7bf52..2d159d2e220 100644 --- a/crates/router/src/core/fraud_check/operation.rs +++ b/crates/router/src/core/fraud_check/operation.rs @@ -14,7 +14,6 @@ use crate::{ errors::{self, RouterResult}, payments, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, types::{domain, fraud_check::FrmRouterData}, }; @@ -101,7 +100,7 @@ pub trait Domain<F>: Send + Sync { pub trait UpdateTracker<D, F: Clone>: Send { async fn update_tracker<'b>( &'b self, - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, frm_data: D, payment_data: &mut payments::PaymentData<F>, diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs index 7c97eee8b49..698eb43385e 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs @@ -19,7 +19,6 @@ use crate::{ }, payments, }, - db::StorageInterface, errors, routes::app::ReqState, services::{self, api}, @@ -329,13 +328,14 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPost { impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost { async fn update_tracker<'b>( &'b self, - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, mut frm_data: FrmData, payment_data: &mut payments::PaymentData<F>, frm_suggestion: Option<FrmSuggestion>, frm_router_data: FrmRouterData, ) -> RouterResult<FrmData> { + let db = &*state.store; let frm_check_update = match frm_router_data.response { FrmResponse::Sale(response) => match response { Err(err) => Some(FraudCheckUpdate::ErrorUpdate { @@ -515,6 +515,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost { payment_data.payment_intent = db .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), PaymentIntentUpdate::RejectUpdate { status: payment_intent_status, diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs index c153acc7544..6a0bd78130d 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs @@ -16,7 +16,6 @@ use crate::{ }, payments, }, - db::StorageInterface, errors, routes::app::ReqState, types::{ @@ -218,7 +217,7 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPre { impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPre { async fn update_tracker<'b>( &'b self, - db: &dyn StorageInterface, + state: &SessionState, _key_store: &domain::MerchantKeyStore, mut frm_data: FrmData, payment_data: &mut payments::PaymentData<F>, @@ -337,6 +336,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPre { }), }; + let db = &*state.store; frm_data.fraud_check = match frm_check_update { Some(fraud_check_update) => db .update_fraud_check_response_with_attempt_id( diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index 24ba06bcf36..22b3b29e03b 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -17,10 +17,11 @@ pub async fn rust_locker_migration( merchant_id: &str, ) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> { let db = state.store.as_ref(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -28,13 +29,13 @@ pub async fn rust_locker_migration( .change_context(errors::ApiErrorResponse::InternalServerError)?; let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .change_context(errors::ApiErrorResponse::InternalServerError)?; let domain_customers = db - .list_customers_by_merchant_id(merchant_id, &key_store) + .list_customers_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs index 2bb981d03e8..a4eb18371f0 100644 --- a/crates/router/src/core/mandate/helpers.rs +++ b/crates/router/src/core/mandate/helpers.rs @@ -21,6 +21,7 @@ pub async fn get_profile_id_for_mandate( let pi = state .store .find_payment_intent_by_payment_id_merchant_id( + &state.into(), payment_id, &merchant_account.merchant_id, key_store, diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 49e4885dc93..bf50405ba81 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -59,6 +59,7 @@ pub async fn initiate_payment_link_flow( let db = &*state.store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payment_id, &merchant_id, &key_store, @@ -497,6 +498,7 @@ pub async fn get_payment_link_status( let db = &*state.store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payment_id, &merchant_id, &key_store, diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index b9e21b616c0..86cb1fc1b1e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -266,6 +266,7 @@ pub async fn render_pm_collect_link( // Fetch customer let customer = db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &customer_id, &req.merchant_id, &key_store, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 468bc0dbfc3..431826fbdb0 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -23,11 +23,15 @@ use common_enums::enums::MerchantStorageScheme; use common_utils::{ consts, crypto::Encryptable, + encryption::Encryption, ext_traits::{AsyncExt, Encode, StringExt, ValueExt}, generate_id, id_type, - types::MinorUnit, + types::{ + keymanager::{Identifier, KeyManagerState}, + MinorUnit, + }, }; -use diesel_models::{business_profile::BusinessProfile, encryption::Encryption, payment_method}; +use diesel_models::{business_profile::BusinessProfile, payment_method}; use domain::CustomerUpdate; use error_stack::{report, ResultExt}; use euclid::{ @@ -77,7 +81,7 @@ use crate::{ #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_payment_method( - db: &dyn db::StorageInterface, + state: &routes::SessionState, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, payment_method_id: &str, @@ -94,8 +98,10 @@ pub async fn create_payment_method( payment_method_billing_address: Option<Encryption>, card_scheme: Option<String>, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { + let db = &*state.store; let customer = db .find_customer_by_customer_id_merchant_id( + &state.into(), customer_id, merchant_id, key_store, @@ -153,7 +159,7 @@ pub async fn create_payment_method( if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { let _ = set_default_payment_method( - db, + state, merchant_id.to_string(), key_store.clone(), customer_id, @@ -197,7 +203,7 @@ pub fn store_default_payment_method( } #[instrument(skip_all)] pub async fn get_or_insert_payment_method( - db: &dyn db::StorageInterface, + state: &routes::SessionState, req: api::PaymentMethodCreate, resp: &mut api::PaymentMethodResponse, merchant_account: &domain::MerchantAccount, @@ -206,6 +212,7 @@ pub async fn get_or_insert_payment_method( ) -> errors::RouterResult<diesel_models::PaymentMethod> { let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; + let db = &*state.store; let payment_method = { let existing_pm_by_pmid = db .find_payment_method(&payment_method_id, merchant_account.storage_scheme) @@ -240,7 +247,7 @@ pub async fn get_or_insert_payment_method( Err(err) => { if err.current_context().is_db_not_found() { insert_payment_method( - db, + state, resp, &req, key_store, @@ -278,7 +285,7 @@ pub async fn migrate_payment_method( if let Some(connector_mandate_details) = &req.connector_mandate_details { helpers::validate_merchant_connector_ids_in_connector_mandate_details( - &*state.store, + &state, key_store, connector_mandate_details, merchant_id, @@ -294,7 +301,7 @@ pub async fn migrate_payment_method( &req, ); get_client_secret_or_add_payment_method( - state, + &state, payment_method_create_request, merchant_account, key_store, @@ -338,7 +345,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(key_store, billing)) + .async_map(|billing| create_encrypted_data(&state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -346,6 +353,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( let customer = db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &customer_id, &merchant_id, key_store, @@ -475,7 +483,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = payment_method_card_details - .async_map(|card_details| create_encrypted_data(key_store, card_details)) + .async_map(|card_details| create_encrypted_data(&state, key_store, card_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -535,7 +543,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { let _ = set_default_payment_method( - &*state.store, + &state, merchant_id.to_string(), key_store.clone(), &customer_id, @@ -572,12 +580,11 @@ pub fn get_card_bin_and_last4_digits_for_masked_card( #[instrument(skip_all)] pub async fn get_client_secret_or_add_payment_method( - state: routes::SessionState, + state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { - let db = &*state.store; let merchant_id = &merchant_account.merchant_id; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; @@ -589,7 +596,7 @@ pub async fn get_client_secret_or_add_payment_method( let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(key_store, billing)) + .async_map(|billing| create_encrypted_data(state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -608,7 +615,7 @@ pub async fn get_client_secret_or_add_payment_method( let payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let res = create_payment_method( - db, + state, &req, &customer_id, payment_method_id.as_str(), @@ -629,7 +636,7 @@ pub async fn get_client_secret_or_add_payment_method( if res.status == enums::PaymentMethodStatus::AwaitingData { add_payment_method_status_update_task( - db, + &*state.store, &res, enums::PaymentMethodStatus::AwaitingData, enums::PaymentMethodStatus::Inactive, @@ -708,6 +715,7 @@ pub async fn add_payment_method_data( let customer_id = payment_method.customer_id.clone(); let customer = db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &customer_id, &merchant_account.merchant_id, &key_store, @@ -754,7 +762,7 @@ pub async fn add_payment_method_data( .attach_printable("Failed to add payment method in db")?; get_or_insert_payment_method( - db, + &state, req.clone(), &mut pm_resp, &merchant_account, @@ -795,6 +803,7 @@ pub async fn add_payment_method_data( let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> = create_encrypted_data( + &state, &key_store, PaymentMethodsData::Card(updated_card), ) @@ -822,7 +831,7 @@ pub async fn add_payment_method_data( if customer.default_payment_method_id.is_none() { let _ = set_default_payment_method( - db, + &state, merchant_account.merchant_id.clone(), key_store.clone(), &customer_id, @@ -864,7 +873,7 @@ pub async fn add_payment_method_data( #[instrument(skip_all)] pub async fn add_payment_method( - state: routes::SessionState, + state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, @@ -877,7 +886,7 @@ pub async fn add_payment_method( let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(key_store, billing)) + .async_map(|billing| create_encrypted_data(state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -894,7 +903,7 @@ pub async fn add_payment_method( #[cfg(feature = "payouts")] api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() { Some(bank) => add_bank_to_locker( - &state, + state, req.clone(), merchant_account, key_store, @@ -923,7 +932,7 @@ pub async fn add_payment_method( &card_details.card_exp_year, )?; Box::pin(add_card_to_locker( - &state, + state, req.clone(), &card_details, &customer_id, @@ -953,7 +962,7 @@ pub async fn add_payment_method( Some(duplication_check) => match duplication_check { payment_methods::DataDuplicationCheck::Duplicated => { let existing_pm = get_or_insert_payment_method( - db, + state, req.clone(), &mut resp, merchant_account, @@ -967,7 +976,7 @@ pub async fn add_payment_method( payment_methods::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = req.card.clone() { let existing_pm = get_or_insert_payment_method( - db, + state, req.clone(), &mut resp, merchant_account, @@ -979,7 +988,7 @@ pub async fn add_payment_method( let client_secret = existing_pm.client_secret.clone(); delete_card_from_locker( - &state, + state, &customer_id, merchant_id, existing_pm @@ -990,7 +999,7 @@ pub async fn add_payment_method( .await?; let add_card_resp = add_card_hs( - &state, + state, req.clone(), &card, &customer_id, @@ -1018,12 +1027,9 @@ pub async fn add_payment_method( .attach_printable("Failed while updating card metadata changes"))? }; - let existing_pm_data = get_card_details_without_locker_fallback( - &existing_pm, - key_store.key.peek(), - &state, - ) - .await?; + let existing_pm_data = + get_card_details_without_locker_fallback(&existing_pm, state, key_store) + .await?; let updated_card = Some(api::CardDetailFromLocker { scheme: existing_pm.scheme.clone(), @@ -1052,7 +1058,9 @@ pub async fn add_payment_method( }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd - .async_map(|updated_pmd| create_encrypted_data(key_store, updated_pmd)) + .async_map(|updated_pmd| { + create_encrypted_data(state, key_store, updated_pmd) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1087,7 +1095,7 @@ pub async fn add_payment_method( }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let pm = insert_payment_method( - db, + state, &resp, &req, key_store, @@ -1112,7 +1120,7 @@ pub async fn add_payment_method( #[allow(clippy::too_many_arguments)] pub async fn insert_payment_method( - db: &dyn db::StorageInterface, + state: &routes::SessionState, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &domain::MerchantKeyStore, @@ -1133,14 +1141,14 @@ pub async fn insert_payment_method( let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details .clone() - .async_map(|pm_card| create_encrypted_data(key_store, pm_card)) + .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; create_payment_method( - db, + state, req, customer_id, &resp.payment_method_id, @@ -1202,7 +1210,9 @@ pub async fn update_customer_payment_method( // Fetch the existing payment method data from db let existing_card_data = decrypt::<serde_json::Value, masking::WithType>( + &(&state).into(), pm.payment_method_data.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.get_inner().peek(), ) .await @@ -1327,7 +1337,7 @@ pub async fn update_customer_payment_method( .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd - .async_map(|updated_pmd| create_encrypted_data(&key_store, updated_pmd)) + .async_map(|updated_pmd| create_encrypted_data(&state, &key_store, updated_pmd)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1445,6 +1455,7 @@ pub async fn add_bank_to_locker( > { let key = key_store.key.get_inner().peek(); let payout_method_data = api::PayoutMethodData::Bank(bank.clone()); + let key_manager_state: KeyManagerState = state.into(); let enc_data = async { serde_json::to_value(payout_method_data.to_owned()) .map_err(|err| { @@ -1458,7 +1469,14 @@ pub async fn add_bank_to_locker( let secret: Secret<String> = Secret::new(v.to_string()); secret }) - .async_lift(|inner| domain::types::encrypt_optional(inner, key)) + .async_lift(|inner| { + domain::types::encrypt_optional( + &key_manager_state, + inner, + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + }) .await } .await @@ -1654,6 +1672,7 @@ pub async fn add_card_hs( #[instrument(skip_all)] pub async fn decode_and_decrypt_locker_data( + state: &routes::SessionState, key_store: &domain::MerchantKeyStore, enc_card_data: String, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { @@ -1664,13 +1683,18 @@ pub async fn decode_and_decrypt_locker_data( .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to decode hex string into bytes")?; // Decrypt - decrypt(Some(Encryption::new(decoded_bytes.into())), key) - .await - .change_context(errors::VaultError::FetchPaymentMethodFailed)? - .map_or( - Err(report!(errors::VaultError::FetchPaymentMethodFailed)), - |d| Ok(d.into_inner()), - ) + decrypt( + &state.into(), + Some(Encryption::new(decoded_bytes.into())), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + .await + .change_context(errors::VaultError::FetchPaymentMethodFailed)? + .map_or( + Err(report!(errors::VaultError::FetchPaymentMethodFailed)), + |d| Ok(d.into_inner()), + ) } #[instrument(skip_all)] @@ -1729,9 +1753,9 @@ pub async fn get_payment_method_from_hs_locker<'a>( .attach_printable( "Failed to retrieve field - enc_card_data from RetrieveCardRespPayload", )?; - decode_and_decrypt_locker_data(key_store, enc_card_data.peek().to_string()).await? + decode_and_decrypt_locker_data(state, key_store, enc_card_data.peek().to_string()).await? } else { - mock_get_payment_method(&*state.store, key_store, payment_method_reference) + mock_get_payment_method(state, key_store, payment_method_reference) .await? .payment_method .payment_method_data @@ -2036,16 +2060,17 @@ pub async fn mock_get_card<'a>( #[instrument(skip_all)] pub async fn mock_get_payment_method<'a>( - db: &dyn db::StorageInterface, + state: &routes::SessionState, key_store: &domain::MerchantKeyStore, card_id: &'a str, ) -> errors::CustomResult<payment_methods::GetPaymentMethodResponse, errors::VaultError> { + let db = &*state.store; let locker_mock_up = db .find_locker_by_card_id(card_id) .await .change_context(errors::VaultError::FetchPaymentMethodFailed)?; let dec_data = if let Some(e) = locker_mock_up.enc_card_data { - decode_and_decrypt_locker_data(key_store, e).await + decode_and_decrypt_locker_data(state, key_store, e).await } else { Err(report!(errors::VaultError::FetchPaymentMethodFailed)) }?; @@ -2187,14 +2212,14 @@ pub async fn list_payment_methods( ) -> errors::RouterResponse<api::PaymentMethodListResponse> { let db = &*state.store; let pm_config_mapping = &state.conf.pm_filters; - + let key_manager_state = &(&state).into(); let payment_intent = if let Some(cs) = &req.client_secret { if cs.starts_with("pm_") { validate_payment_method_and_client_secret(cs, db, &merchant_account).await?; None } else { helpers::verify_payment_intent_time_and_client_secret( - db, + &state, &merchant_account, &key_store, req.client_secret.clone(), @@ -2209,7 +2234,7 @@ pub async fn list_payment_methods( .as_ref() .async_map(|pi| async { helpers::get_address_by_id( - db, + &state, pi.shipping_address_id.clone(), &key_store, &pi.payment_id, @@ -2226,7 +2251,7 @@ pub async fn list_payment_methods( .as_ref() .async_map(|pi| async { helpers::get_address_by_id( - db, + &state, pi.billing_address_id.clone(), &key_store, &pi.payment_id, @@ -2246,6 +2271,7 @@ pub async fn list_payment_methods( .as_ref() .async_and_then(|cust| async { db.find_customer_by_customer_id_merchant_id( + key_manager_state, cust, &pi.merchant_id, &key_store, @@ -2293,6 +2319,7 @@ pub async fn list_payment_methods( let all_mcas = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, &merchant_account.merchant_id, false, &key_store, @@ -3273,6 +3300,7 @@ pub async fn call_surcharge_decision_management( let _ = state .store .update_payment_intent( + &(&state).into(), payment_intent, storage::PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable: true, @@ -3322,6 +3350,7 @@ pub async fn call_surcharge_decision_management_for_saved_card( let _ = state .store .update_payment_intent( + &state.into(), payment_intent, storage::PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable: true, @@ -3586,7 +3615,6 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( customer_id: Option<&id_type::CustomerId>, ephemeral_api_key: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { - let db = state.store.as_ref(); let limit = req.clone().and_then(|pml_req| pml_req.limit); let auth_cust = if let Some(key) = ephemeral_api_key { @@ -3617,7 +3645,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( let cloned_secret = req.and_then(|r| r.client_secret.as_ref().cloned()); let payment_intent: Option<hyperswitch_domain_models::payments::PaymentIntent> = helpers::verify_payment_intent_time_and_client_secret( - db, + &state, &merchant_account, &key_store, cloned_secret, @@ -3671,6 +3699,7 @@ pub async fn list_customer_payment_method( let customer = db .find_customer_by_customer_id_merchant_id( + &state.into(), customer_id, &merchant_account.merchant_id, &key_store, @@ -3679,8 +3708,6 @@ pub async fn list_customer_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - let key = key_store.key.get_inner().peek(); - let is_requires_cvv = db .find_config_by_key_unwrap_or( format!("{}_requires_cvv", merchant_account.merchant_id).as_str(), @@ -3741,7 +3768,8 @@ pub async fn list_customer_payment_method( let payment_method_retrieval_context = match payment_method { enums::PaymentMethod::Card => { - let card_details = get_card_details_with_locker_fallback(&pm, key, state).await?; + let card_details = + get_card_details_with_locker_fallback(&pm, state, &key_store).await?; if card_details.is_some() { PaymentMethodListContext { @@ -3761,12 +3789,13 @@ 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_token_data = get_bank_account_connector_details(&pm, key) - .await - .unwrap_or_else(|error| { - logger::error!(?error); - None - }); + let bank_account_token_data = + get_bank_account_connector_details(state, &pm, &key_store) + .await + .unwrap_or_else(|error| { + logger::error!(?error); + None + }); if let Some(data) = bank_account_token_data { let token_data = PaymentTokenData::AuthBankDebit(data); @@ -3822,7 +3851,7 @@ pub async fn list_customer_payment_method( // Retrieve the masked bank details to be sent as a response let bank_details = if payment_method == enums::PaymentMethod::BankDebit { - get_masked_bank_details(&pm, key) + get_masked_bank_details(state, &pm, &key_store) .await .unwrap_or_else(|error| { logger::error!(?error); @@ -3833,8 +3862,9 @@ pub async fn list_customer_payment_method( }; let payment_method_billing = decrypt_generic_data::<api_models::payments::Address>( + state, pm.payment_method_billing_address, - key, + &key_store, ) .await .attach_printable("unable to decrypt payment method billing address details")?; @@ -3993,6 +4023,7 @@ pub async fn get_mca_status( let mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_id, true, key_store, @@ -4021,17 +4052,21 @@ pub async fn get_mca_status( Ok(false) } pub async fn decrypt_generic_data<T>( + state: &routes::SessionState, data: Option<Encryption>, - key: &[u8], + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<T>> where T: serde::de::DeserializeOwned, { - let decrypted_data = decrypt::<serde_json::Value, masking::WithType>(data, key) - .await - .change_context(errors::StorageError::DecryptionError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to decrypt data")?; + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let decrypted_data = + decrypt::<serde_json::Value, masking::WithType>(&state.into(), data, identifier, key) + .await + .change_context(errors::StorageError::DecryptionError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt data")?; decrypted_data .map(|decrypted_data| decrypted_data.into_inner().expose()) @@ -4043,22 +4078,28 @@ where pub async fn get_card_details_with_locker_fallback( pm: &payment_method::PaymentMethod, - key: &[u8], state: &routes::SessionState, + key_store: &domain::MerchantKeyStore, ) -> 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, - }); + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let card_decrypted = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), + pm.payment_method_data.clone(), + identifier, + 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 { crd.scheme.clone_from(&pm.scheme); @@ -4073,22 +4114,28 @@ pub async fn get_card_details_with_locker_fallback( pub async fn get_card_details_without_locker_fallback( pm: &payment_method::PaymentMethod, - key: &[u8], state: &routes::SessionState, + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<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, - }); + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let card_decrypted = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), + pm.payment_method_data.clone(), + identifier, + 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 { crd.scheme.clone_from(&pm.scheme); @@ -4141,25 +4188,32 @@ pub async fn get_lookup_key_from_locker( } async fn get_masked_bank_details( + state: &routes::SessionState, pm: &payment_method::PaymentMethod, - key: &[u8], + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<MaskedBankDetails>> { - let payment_method_data = - decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) - .await - .change_context(errors::StorageError::DecryptionError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to decrypt bank details")? - .map(|x| x.into_inner().expose()) - .map( - |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { - v.parse_value::<PaymentMethodsData>("PaymentMethodsData") - .change_context(errors::StorageError::DeserializationFailed) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize Payment Method Auth config") - }, - ) - .transpose()?; + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let payment_method_data = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), + pm.payment_method_data.clone(), + identifier, + key, + ) + .await + .change_context(errors::StorageError::DecryptionError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt bank details")? + .map(|x| x.into_inner().expose()) + .map( + |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { + v.parse_value::<PaymentMethodsData>("PaymentMethodsData") + .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize Payment Method Auth config") + }, + ) + .transpose()?; match payment_method_data { Some(pmd) => match pmd { @@ -4174,25 +4228,32 @@ async fn get_masked_bank_details( } async fn get_bank_account_connector_details( + state: &routes::SessionState, pm: &payment_method::PaymentMethod, - key: &[u8], + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<BankAccountTokenData>> { - let payment_method_data = - decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) - .await - .change_context(errors::StorageError::DecryptionError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to decrypt bank details")? - .map(|x| x.into_inner().expose()) - .map( - |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { - v.parse_value::<PaymentMethodsData>("PaymentMethodsData") - .change_context(errors::StorageError::DeserializationFailed) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize Payment Method Auth config") - }, - ) - .transpose()?; + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let payment_method_data = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), + pm.payment_method_data.clone(), + identifier, + key, + ) + .await + .change_context(errors::StorageError::DecryptionError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt bank details")? + .map(|x| x.into_inner().expose()) + .map( + |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { + v.parse_value::<PaymentMethodsData>("PaymentMethodsData") + .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize Payment Method Auth config") + }, + ) + .transpose()?; match payment_method_data { Some(pmd) => match pmd { @@ -4229,17 +4290,20 @@ async fn get_bank_account_connector_details( } } pub async fn set_default_payment_method( - db: &dyn db::StorageInterface, + state: &routes::SessionState, merchant_id: String, key_store: domain::MerchantKeyStore, customer_id: &id_type::CustomerId, payment_method_id: String, storage_scheme: MerchantStorageScheme, ) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> { + let db = &*state.store; + let key_manager_state = &state.into(); // check for the customer // TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value let customer = db .find_customer_by_customer_id_merchant_id( + key_manager_state, customer_id, &merchant_id, &key_store, @@ -4283,6 +4347,7 @@ pub async fn set_default_payment_method( // update the db with the default payment method id let updated_customer_details = db .update_customer_by_customer_id_merchant_id( + key_manager_state, customer_id.to_owned(), merchant_id.to_owned(), customer, @@ -4470,7 +4535,6 @@ pub async fn retrieve_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - let key = key_store.key.peek(); let card = if pm.payment_method == Some(enums::PaymentMethod::Card) { let card_detail = if state.conf.locker.locker_enabled { let card = get_card_from_locker( @@ -4486,7 +4550,7 @@ pub async fn retrieve_payment_method( .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? + get_card_details_without_locker_fallback(&pm, &state, &key_store).await? }; Some(card_detail) } else { @@ -4521,6 +4585,7 @@ pub async fn delete_payment_method( key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key = db .find_payment_method( pm_id.payment_method_id.as_str(), @@ -4531,6 +4596,7 @@ pub async fn delete_payment_method( let customer = db .find_customer_by_customer_id_merchant_id( + key_manager_state, &key.customer_id, &merchant_account.merchant_id, &key_store, @@ -4570,6 +4636,7 @@ pub async fn delete_payment_method( }; db.update_customer_by_customer_id_merchant_id( + key_manager_state, key.customer_id, key.merchant_id, customer, @@ -4591,6 +4658,7 @@ pub async fn delete_payment_method( } pub async fn create_encrypted_data<T>( + state: &routes::SessionState, key_store: &domain::MerchantKeyStore, data: T, ) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>> @@ -4598,6 +4666,8 @@ where T: Debug + serde::Serialize, { let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let key_manager_state: KeyManagerState = state.into(); let encoded_data = Encode::encode_to_value(&data) .change_context(errors::StorageError::SerializationFailed) @@ -4605,10 +4675,11 @@ where let secret_data = Secret::<_, masking::WithType>::new(encoded_data); - let encrypted_data = domain::types::encrypt(secret_data, key) - .await - .change_context(errors::StorageError::EncryptionError) - .attach_printable("Unable to encrypt data")?; + let encrypted_data = + domain::types::encrypt(&key_manager_state, secret_data, identifier.clone(), key) + .await + .change_context(errors::StorageError::EncryptionError) + .attach_printable("Unable to encrypt data")?; Ok(encrypted_data) } diff --git a/crates/router/src/core/payment_methods/validator.rs b/crates/router/src/core/payment_methods/validator.rs index be34d3db38c..23470fb3ef1 100644 --- a/crates/router/src/core/payment_methods/validator.rs +++ b/crates/router/src/core/payment_methods/validator.rs @@ -27,6 +27,7 @@ pub async fn validate_request_and_initiate_payment_method_collect_link( let merchant_id = merchant_account.merchant_id.clone(); match db .find_customer_by_customer_id_merchant_id( + &state.into(), &customer_id, &merchant_id, key_store, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 5cad096bd39..9c420c1e44d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -164,7 +164,7 @@ where let (operation, customer) = operation .to_domain()? .get_or_create_customer_details( - &*state.store, + state, &mut payment_data, customer_details, &key_store, @@ -208,8 +208,6 @@ where // Fetch and check FRM configs #[cfg(feature = "frm")] let mut frm_info = None; - #[cfg(feature = "frm")] - let db = &*state.store; #[allow(unused_variables, unused_mut)] let mut should_continue_transaction: bool = true; #[cfg(feature = "frm")] @@ -217,7 +215,6 @@ where #[cfg(feature = "frm")] let frm_configs = if state.conf.frm.enabled { Box::pin(frm_core::call_frm_before_connector_call( - db, &operation, &merchant_account, &mut payment_data, @@ -1203,6 +1200,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, &merchant_id, &merchant_key_store, @@ -2883,7 +2881,7 @@ pub async fn list_payments( let merchant_id = &merchant.merchant_id; let db = state.store.as_ref(); let payment_intents = helpers::filter_by_constraints( - db, + &state, &constraints, merchant_id, &key_store, @@ -2955,6 +2953,7 @@ pub async fn apply_filters_on_payments( let db = state.store.as_ref(); let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db .get_filtered_payment_intents_attempt( + &(&state).into(), &merchant.merchant_id, &constraints.clone().into(), &merchant_key_store, @@ -3008,6 +3007,7 @@ pub async fn get_filters_for_payments( let db = state.store.as_ref(); let pi = db .filter_payment_intents_by_time_range_constraints( + &(&state).into(), &merchant.merchant_id, &time_range, &merchant_key_store, @@ -4021,6 +4021,7 @@ pub async fn payment_external_authentication( let payment_id = req.payment_id; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payment_id, merchant_id, &key_store, @@ -4054,6 +4055,7 @@ pub async fn payment_external_authentication( state .store .find_customer_by_customer_id_merchant_id( + &(&state).into(), customer_id, &merchant_account.merchant_id, &key_store, @@ -4076,7 +4078,7 @@ pub async fn payment_external_authentication( let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let shipping_address = helpers::create_or_find_address_for_payment_by_request( - db, + &state, None, payment_intent.shipping_address_id.as_deref(), merchant_id, @@ -4087,7 +4089,7 @@ pub async fn payment_external_authentication( ) .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( - db, + &state, None, payment_intent.billing_address_id.as_deref(), merchant_id, @@ -4259,9 +4261,11 @@ pub async fn payments_manual_update( error_message, error_reason, } = req; + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -4270,7 +4274,7 @@ pub async fn payments_manual_update( .attach_printable("Error while fetching the key store by merchant_id")?; let merchant_account = state .store - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; @@ -4290,6 +4294,7 @@ pub async fn payments_manual_update( let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payment_id, &merchant_account.merchant_id, &key_store, @@ -4345,6 +4350,7 @@ pub async fn payments_manual_update( state .store .update_payment_intent( + &(&state).into(), payment_intent, payment_intent_update, &key_store, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 3629457d5ab..ecf8ff0c40d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,8 +1,9 @@ use std::{borrow::Cow, str::FromStr}; use api_models::{ + customers::CustomerRequestWithEmail, mandates::RecurringDetails, - payments::{CardToken, GetPaymentMethodType, RequestSurchargeDetails}, + payments::{AddressDetailsWithPhone, CardToken, GetPaymentMethodType, RequestSurchargeDetails}, }; use base64::Engine; use common_enums::ConnectorType; @@ -10,7 +11,10 @@ use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, fp_utils, generate_id, id_type, pii, - types::MinorUnit, + types::{ + keymanager::{Identifier, KeyManagerState, ToEncryptable}, + MinorUnit, + }, }; use diesel_models::enums::{self}; // TODO : Evaluate all the helper functions () @@ -139,7 +143,7 @@ pub fn filter_mca_based_on_connector_type( #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_or_update_address_for_payment_by_request( - db: &dyn StorageInterface, + session_state: &SessionState, req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &str, @@ -149,87 +153,54 @@ pub async fn create_or_update_address_for_payment_by_request( storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); - + let db = &session_state.store; + let key_manager_state = &session_state.into(); Ok(match address_id { Some(id) => match req_address { Some(address) => { - let address_update = async { - Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( - storage::AddressUpdate::Update { - city: address - .address - .as_ref() - .and_then(|value| value.city.clone()), - country: address.address.as_ref().and_then(|value| value.country), - line1: address - .address - .as_ref() - .and_then(|value| value.line1.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - line2: address - .address - .as_ref() - .and_then(|value| value.line2.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - line3: address - .address - .as_ref() - .and_then(|value| value.line3.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - state: address - .address - .as_ref() - .and_then(|value| value.state.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - zip: address - .address - .as_ref() - .and_then(|value| value.zip.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - first_name: address - .address - .as_ref() - .and_then(|value| value.first_name.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - last_name: address - .address - .as_ref() - .and_then(|value| value.last_name.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - phone_number: address - .phone - .as_ref() - .and_then(|value| value.number.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - country_code: address - .phone - .as_ref() - .and_then(|value| value.country_code.clone()), - updated_by: storage_scheme.to_string(), - email: address - .email - .as_ref() - .cloned() - .async_lift(|inner| { - types::encrypt_optional(inner.map(|inner| inner.expose()), key) - }) - .await?, - }, - ) - } + let encrypted_data = types::batch_encrypt( + &session_state.into(), + AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone { + address: address.address.clone(), + phone_number: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + email: address.email.clone(), + }), + Identifier::Merchant(merchant_key_store.merchant_id.clone()), + key, + ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address")?; + let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting address")?; + let address_update = storage::AddressUpdate::Update { + city: address + .address + .as_ref() + .and_then(|value| value.city.clone()), + country: address.address.as_ref().and_then(|value| value.country), + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + state: encryptable_address.state, + zip: encryptable_address.zip, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, + phone_number: encryptable_address.phone_number, + country_code: address + .phone + .as_ref() + .and_then(|value| value.country_code.clone()), + updated_by: storage_scheme.to_string(), + email: encryptable_address.email, + }; let address = db .find_address_by_merchant_id_payment_id_address_id( + key_manager_state, merchant_id, payment_id, id, @@ -241,6 +212,7 @@ pub async fn create_or_update_address_for_payment_by_request( .attach_printable("Error while fetching address")?; Some( db.update_address_for_payments( + key_manager_state, address, address_update, payment_id.to_string(), @@ -254,6 +226,7 @@ pub async fn create_or_update_address_for_payment_by_request( } None => Some( db.find_address_by_merchant_id_payment_id_address_id( + key_manager_state, merchant_id, payment_id, id, @@ -268,10 +241,11 @@ pub async fn create_or_update_address_for_payment_by_request( }, None => match req_address { Some(address) => { - let address = get_domain_address(address, merchant_id, key, storage_scheme) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while encrypting address while insert")?; + let address = + get_domain_address(session_state, address, merchant_id, key, storage_scheme) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting address while insert")?; let payment_address = domain::PaymentAddress { address, @@ -281,6 +255,7 @@ pub async fn create_or_update_address_for_payment_by_request( Some( db.insert_address_for_payments( + key_manager_state, payment_id, payment_address, merchant_key_store, @@ -301,7 +276,7 @@ pub async fn create_or_update_address_for_payment_by_request( #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_or_find_address_for_payment_by_request( - db: &dyn StorageInterface, + state: &SessionState, req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &str, @@ -311,10 +286,12 @@ pub async fn create_or_find_address_for_payment_by_request( storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); - + let db = &state.store; + let key_manager_state = &state.into(); Ok(match address_id { Some(id) => Some( db.find_address_by_merchant_id_payment_id_address_id( + key_manager_state, merchant_id, payment_id, id, @@ -329,7 +306,7 @@ pub async fn create_or_find_address_for_payment_by_request( None => match req_address { Some(address) => { // generate a new address here - let address = get_domain_address(address, merchant_id, key, storage_scheme) + let address = get_domain_address(state, address, merchant_id, key, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address while insert")?; @@ -342,6 +319,7 @@ pub async fn create_or_find_address_for_payment_by_request( Some( db.insert_address_for_payments( + key_manager_state, payment_id, payment_address, merchant_key_store, @@ -359,70 +337,56 @@ pub async fn create_or_find_address_for_payment_by_request( } pub async fn get_domain_address( + session_state: &SessionState, address: &api_models::payments::Address, merchant_id: &str, key: &[u8], storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<domain::Address, common_utils::errors::CryptoError> { async { - let address_details = address.address.as_ref(); + let address_details = &address.address.as_ref(); + let encrypted_data = types::batch_encrypt( + &session_state.into(), + AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone { + address: address_details.cloned(), + phone_number: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + email: address.email.clone(), + }), + Identifier::Merchant(merchant_id.to_string()), + key, + ) + .await?; + let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(domain::Address { id: None, - phone_number: address - .phone - .as_ref() - .and_then(|a| a.number.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, + phone_number: encryptable_address.phone_number, country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()), merchant_id: merchant_id.to_string(), address_id: generate_id(consts::ID_LENGTH, "add"), city: address_details.and_then(|address_details| address_details.city.clone()), country: address_details.and_then(|address_details| address_details.country), - line1: address_details - .and_then(|address_details| address_details.line1.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - line2: address_details - .and_then(|address_details| address_details.line2.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - line3: address_details - .and_then(|address_details| address_details.line3.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - state: address_details - .and_then(|address_details| address_details.state.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + state: encryptable_address.state, created_at: common_utils::date_time::now(), - first_name: address_details - .and_then(|address_details| address_details.first_name.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - last_name: address_details - .and_then(|address_details| address_details.last_name.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, modified_at: common_utils::date_time::now(), - zip: address_details - .and_then(|address_details| address_details.zip.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, + zip: encryptable_address.zip, updated_by: storage_scheme.to_string(), - email: address - .email - .as_ref() - .cloned() - .async_lift(|inner| types::encrypt_optional(inner.map(|inner| inner.expose()), key)) - .await?, + email: encryptable_address.email, }) } .await } pub async fn get_address_by_id( - db: &dyn StorageInterface, + state: &SessionState, address_id: Option<String>, merchant_key_store: &domain::MerchantKeyStore, payment_id: &str, @@ -431,17 +395,21 @@ pub async fn get_address_by_id( ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { match address_id { None => Ok(None), - Some(address_id) => Ok(db - .find_address_by_merchant_id_payment_id_address_id( - merchant_id, - payment_id, - &address_id, - merchant_key_store, - storage_scheme, - ) - .await - .map(|payment_address| payment_address.address) - .ok()), + Some(address_id) => { + let db = &*state.store; + Ok(db + .find_address_by_merchant_id_payment_id_address_id( + &state.into(), + merchant_id, + payment_id, + &address_id, + merchant_key_store, + storage_scheme, + ) + .await + .map(|payment_address| payment_address.address) + .ok()) + } } } @@ -688,12 +656,13 @@ pub async fn get_token_for_recurring_mandate( ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; - + let key_manager_state: KeyManagerState = state.into(); let original_payment_intent = mandate .original_payment_id .as_ref() .async_map(|payment_id| async { db.find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, payment_id, &mandate.merchant_id, merchant_key_store, @@ -1429,7 +1398,7 @@ pub(crate) async fn get_payment_method_create_request( } pub async fn get_customer_from_details<F: Clone>( - db: &dyn StorageInterface, + state: &SessionState, customer_id: Option<id_type::CustomerId>, merchant_id: &str, payment_data: &mut PaymentData<F>, @@ -1439,8 +1408,10 @@ pub async fn get_customer_from_details<F: Clone>( match customer_id { None => Ok(None), Some(customer_id) => { + let db = &*state.store; let customer = db .find_customer_optional_by_customer_id_merchant_id( + &state.into(), &customer_id, merchant_id, merchant_key_store, @@ -1549,8 +1520,8 @@ pub async fn get_connector_default( #[instrument(skip_all)] #[allow(clippy::type_complexity)] pub async fn create_customer_if_not_exist<'a, F: Clone, R>( + state: &SessionState, operation: BoxedOperation<'a, F, R>, - db: &dyn StorageInterface, payment_data: &mut PaymentData<F>, req: Option<CustomerDetails>, merchant_id: &str, @@ -1613,7 +1584,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( payment_data.payment_intent.customer_details = raw_customer_details .clone() - .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .async_map(|customer_details| create_encrypted_data(state, key_store, customer_details)) .await .transpose() .change_context(errors::StorageError::EncryptionError) @@ -1622,18 +1593,36 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( let customer_id = request_customer_details .customer_id .or(payment_data.payment_intent.customer_id.clone()); - + let db = &*state.store; + let key_manager_state = &state.into(); let optional_customer = match customer_id { Some(customer_id) => { let customer_data = db .find_customer_optional_by_customer_id_merchant_id( + key_manager_state, &customer_id, merchant_id, key_store, storage_scheme, ) .await?; - + let key = key_store.key.get_inner().peek(); + let encrypted_data = types::batch_encrypt( + key_manager_state, + CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail { + name: request_customer_details.name.clone(), + email: request_customer_details.email.clone(), + phone: request_customer_details.phone.clone(), + }), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + .await + .change_context(errors::StorageError::SerializationFailed) + .attach_printable("Failed while encrypting Customer while Update")?; + let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) + .change_context(errors::StorageError::SerializationFailed) + .attach_printable("Failed while encrypting Customer while Update")?; Some(match customer_data { Some(c) => { // Update the customer data if new data is passed in the request @@ -1642,44 +1631,19 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( | request_customer_details.phone.is_some() | request_customer_details.phone_country_code.is_some() { - let key = key_store.key.get_inner().peek(); - let customer_update = async { - Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( - Update { - name: request_customer_details - .name - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - email: request_customer_details - .email - .clone() - .async_lift(|inner| { - types::encrypt_optional( - inner.map(|inner| inner.expose()), - key, - ) - }) - .await?, - phone: Box::new( - request_customer_details - .phone - .clone() - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - ), - phone_country_code: request_customer_details.phone_country_code, - description: None, - connector_customer: None, - metadata: None, - address_id: None, - }, - ) - } - .await - .change_context(errors::StorageError::SerializationFailed) - .attach_printable("Failed while encrypting Customer while Update")?; + let customer_update = Update { + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: Box::new(encryptable_customer.phone), + phone_country_code: request_customer_details.phone_country_code, + description: None, + connector_customer: None, + metadata: None, + address_id: None, + }; db.update_customer_by_customer_id_merchant_id( + key_manager_state, customer_id, merchant_id.to_string(), c, @@ -1693,51 +1657,25 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( } } None => { - let new_customer = async { - let key = key_store.key.get_inner().peek(); - Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( - domain::Customer { - customer_id, - merchant_id: merchant_id.to_string(), - name: request_customer_details - .name - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - email: request_customer_details - .email - .clone() - .async_lift(|inner| { - types::encrypt_optional( - inner.map(|inner| inner.expose()), - key, - ) - }) - .await?, - phone: request_customer_details - .phone - .clone() - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - phone_country_code: request_customer_details - .phone_country_code - .clone(), - description: None, - created_at: common_utils::date_time::now(), - id: None, - metadata: None, - modified_at: common_utils::date_time::now(), - connector_customer: None, - address_id: None, - default_payment_method_id: None, - updated_by: None, - }, - ) - } - .await - .change_context(errors::StorageError::SerializationFailed) - .attach_printable("Failed while encrypting Customer while insert")?; + let new_customer = domain::Customer { + customer_id, + merchant_id: merchant_id.to_string(), + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: encryptable_customer.phone, + phone_country_code: request_customer_details.phone_country_code.clone(), + description: None, + created_at: common_utils::date_time::now(), + id: None, + metadata: None, + modified_at: common_utils::date_time::now(), + connector_customer: None, + address_id: None, + default_payment_method_id: None, + updated_by: None, + }; metrics::CUSTOMER_CREATED.add(&metrics::CONTEXT, 1, &[]); - db.insert_customer(new_customer, key_store, storage_scheme) + db.insert_customer(key_manager_state, new_customer, key_store, storage_scheme) .await } }) @@ -1746,6 +1684,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( None => None, Some(customer_id) => db .find_customer_optional_by_customer_id_merchant_id( + key_manager_state, customer_id, merchant_id, key_store, @@ -2533,14 +2472,16 @@ where #[cfg(feature = "olap")] pub(super) async fn filter_by_constraints( - db: &dyn StorageInterface, + state: &SessionState, constraints: &api::PaymentListConstraints, merchant_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, errors::DataStorageError> { + let db = &*state.store; let result = db .filter_payment_intent_by_constraints( + &(state).into(), merchant_id, &constraints.clone().into(), key_store, @@ -2957,17 +2898,19 @@ pub(crate) fn validate_pm_or_token_given( // A function to perform database lookup and then verify the client secret pub async fn verify_payment_intent_time_and_client_secret( - db: &dyn StorageInterface, + state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { + let db = &*state.store; client_secret .async_map(|cs| async move { let payment_id = get_payment_id_from_client_secret(&cs)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, &merchant_account.merchant_id, key_store, @@ -3371,6 +3314,7 @@ pub async fn get_merchant_connector_account( merchant_connector_id: Option<&String>, ) -> RouterResult<MerchantConnectorAccountType> { let db = &*state.store; + let key_manager_state = &state.into(); match creds_identifier { Some(creds_identifier) => { let key = format!("mcd_{merchant_id}_{creds_identifier}"); @@ -3445,6 +3389,7 @@ pub async fn get_merchant_connector_account( None => { if let Some(merchant_connector_id) = merchant_connector_id { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, merchant_id, merchant_connector_id, key_store, @@ -3457,6 +3402,7 @@ pub async fn get_merchant_connector_account( ) } else { db.find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, profile_id, connector_name, key_store, @@ -3737,13 +3683,14 @@ impl AttemptType { request: &api::PaymentsRequest, fetched_payment_intent: PaymentIntent, fetched_payment_attempt: PaymentAttempt, - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<(PaymentIntent, PaymentAttempt)> { match self { Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)), Self::New => { + let db = &*state.store; let new_attempt_count = fetched_payment_intent.attempt_count + 1; let new_payment_attempt = db .insert_payment_attempt( @@ -3766,6 +3713,7 @@ impl AttemptType { let updated_payment_intent = db .update_payment_intent( + &state.into(), fetched_payment_intent, storage::PaymentIntentUpdate::StatusAndAttemptUpdate { status: payment_intent_status_fsm( @@ -4159,6 +4107,7 @@ pub fn is_apple_pay_simplified_flow( } pub async fn get_encrypted_apple_pay_connector_wallets_details( + state: &SessionState, key_store: &domain::MerchantKeyStore, connector_metadata: &Option<masking::Secret<tera::Value>>, ) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> { @@ -4179,10 +4128,15 @@ pub async fn get_encrypted_apple_pay_connector_wallets_details( }) .transpose()? .map(masking::Secret::new); - + let key_manager_state: KeyManagerState = state.into(); let encrypted_connector_apple_pay_details = connector_apple_pay_details .async_lift(|wallets_details| { - types::encrypt_optional(wallets_details, key_store.key.get_inner().peek()) + types::encrypt_optional( + &key_manager_state, + wallets_details, + Identifier::Merchant(key_store.merchant_id.clone()), + key_store.key.get_inner().peek(), + ) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -4266,6 +4220,7 @@ where let merchant_connector_account_list = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_account.merchant_id.as_str(), false, key_store, @@ -5126,13 +5081,15 @@ pub async fn override_setup_future_usage_to_on_session<F: Clone>( } pub async fn validate_merchant_connector_ids_in_connector_mandate_details( - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, connector_mandate_details: &api_models::payment_methods::PaymentsMandateReference, merchant_id: &str, ) -> CustomResult<(), errors::ApiErrorResponse> { + let db = &*state.store; let merchant_connector_account_list = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_id, true, key_store, diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index be54ead0ac1..70cc77aa536 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -28,7 +28,6 @@ pub use self::{ use super::{helpers, CustomerDetails, PaymentData}; use crate::{ core::errors::{self, CustomResult, RouterResult}, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -117,7 +116,7 @@ pub trait Domain<F: Clone, R>: Send + Sync { /// This will fetch customer details, (this operation is flow specific) async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, @@ -259,7 +258,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, @@ -274,7 +273,7 @@ where Ok(( Box::new(self), helpers::get_customer_from_details( - db, + state, payment_data.payment_intent.customer_id.clone(), &merchant_key_store.merchant_id, payment_data, @@ -334,7 +333,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, @@ -349,7 +348,7 @@ where Ok(( Box::new(self), helpers::get_customer_from_details( - db, + state, payment_data.payment_intent.customer_id.clone(), &merchant_key_store.merchant_id, payment_data, @@ -408,7 +407,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, @@ -423,7 +422,7 @@ where Ok(( Box::new(self), helpers::get_customer_from_details( - db, + state, payment_data.payment_intent.customer_id.clone(), &merchant_key_store.merchant_id, payment_data, @@ -483,7 +482,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - _db: &dyn StorageInterface, + _state: &SessionState, _payment_data: &mut PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 172c5943c0c..5b18512fe20 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -53,6 +53,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -97,7 +98,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -107,7 +108,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -117,7 +118,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -199,7 +200,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, - db: &'b SessionState, + state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, @@ -224,9 +225,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for merchant_decision: Some(api_models::enums::MerchantDecision::Approved.to_string()), updated_by: storage_scheme.to_string(), }; - payment_data.payment_intent = db + payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, intent_status_update, key_store, @@ -234,7 +236,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - db.store + state + .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), storage::PaymentAttemptUpdate::StatusUpdate { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 94591d44e4b..a8a2756a58d 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -51,6 +51,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -82,7 +83,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -92,7 +93,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -102,7 +103,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -212,7 +213,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, - db: &'b SessionState, + state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, @@ -242,9 +243,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for }; if let Some(payment_intent_update) = intent_status_update { - payment_data.payment_intent = db + payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, payment_intent_update, key_store, @@ -254,7 +256,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } - db.store + state + .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), storage::PaymentAttemptUpdate::VoidUpdate { diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index f6e6dee14a5..03a3d031e1a 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -54,6 +54,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -135,7 +136,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -145,7 +146,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -155,7 +156,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 9c48df1dd53..c6875392750 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -17,7 +17,6 @@ use crate::{ }, utils as core_utils, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -56,6 +55,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -200,7 +200,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co )?; let shipping_address = helpers::create_or_update_address_for_payment_by_request( - db, + state, request.shipping.as_ref(), payment_intent.shipping_address_id.clone().as_deref(), merchant_id.as_ref(), @@ -216,7 +216,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co .map(|shipping_address| shipping_address.address_id.clone()); let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -226,7 +226,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -364,7 +364,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -377,8 +377,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -478,6 +478,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple let updated_payment_intent = db .update_payment_intent( + &state.into(), payment_intent, payment_intent_update, key_store, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 2955b0c3850..addd2f30670 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -7,7 +7,10 @@ use api_models::{ payments::{AdditionalPaymentData, ExtendedCardInfo}, }; use async_trait::async_trait; -use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt}; +use common_utils::{ + ext_traits::{AsyncExt, Encode, StringExt, ValueExt}, + types::keymanager::Identifier, +}; use error_stack::{report, ResultExt}; use futures::FutureExt; use hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdateFields; @@ -30,7 +33,6 @@ use crate::{ }, utils as core_utils, }, - db::StorageInterface, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, @@ -74,6 +76,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa // Parallel calls - level 0 let mut payment_intent = store .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, m_merchant_id.as_str(), key_store, @@ -181,13 +184,13 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let m_payment_intent_payment_id = payment_intent.payment_id.clone(); let m_customer_details_customer_id = customer_details.customer_id.clone(); let m_payment_intent_customer_id = payment_intent.customer_id.clone(); - let store = state.clone().store; let m_key_store = key_store.clone(); + let session_state = state.clone(); let shipping_address_fut = tokio::spawn( async move { helpers::create_or_update_address_for_payment_by_request( - store.as_ref(), + &session_state, m_request_shipping.as_ref(), m_payment_intent_shipping_address_id.as_deref(), m_merchant_id.as_str(), @@ -209,13 +212,13 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let m_payment_intent_customer_id = payment_intent.customer_id.clone(); let m_payment_intent_billing_address_id = payment_intent.billing_address_id.clone(); let m_payment_intent_payment_id = payment_intent.payment_id.clone(); - let store = state.clone().store; let m_key_store = key_store.clone(); + let session_state = state.clone(); let billing_address_fut = tokio::spawn( async move { helpers::create_or_update_address_for_payment_by_request( - store.as_ref(), + &session_state, m_request_billing.as_ref(), m_payment_intent_billing_address_id.as_deref(), m_merchant_id.as_ref(), @@ -306,7 +309,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa request, payment_intent, payment_attempt, - &*state.store, + state, key_store, storage_scheme, ) @@ -467,8 +470,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .in_current_span(), ); - let store = state.clone().store; - let n_payment_method_billing_address_id = payment_attempt.payment_method_billing_address_id.clone(); let n_request_payment_method_billing_address = request @@ -480,11 +481,12 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let m_key_store = key_store.clone(); let m_customer_details_customer_id = customer_details.customer_id.clone(); let m_merchant_id = merchant_id.clone(); + let session_state = state.clone(); let payment_method_billing_future = tokio::spawn( async move { helpers::create_or_update_address_for_payment_by_request( - store.as_ref(), + &session_state, n_request_payment_method_billing_address.as_ref(), n_payment_method_billing_address_id.as_deref(), m_merchant_id.as_str(), @@ -688,7 +690,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -701,8 +703,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -1077,12 +1079,15 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?; + let key_manager_state = &state.into(); let encode_additional_pm_to_value = if let Some(ref pm) = payment_data.payment_method_info { let key = key_store.key.get_inner().peek(); let card_detail_from_locker: Option<api::CardDetailFromLocker> = decrypt::<serde_json::Value, masking::WithType>( + key_manager_state, pm.payment_method_data.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await @@ -1243,7 +1248,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let billing_address = payment_data.address.get_payment_billing(); let billing_details = billing_address - .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1251,7 +1256,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let shipping_address = payment_data.address.get_shipping(); let shipping_details = shipping_address - .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1273,10 +1278,12 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let m_storage_scheme = storage_scheme.to_string(); let session_expiry = m_payment_data_payment_intent.session_expiry; let m_key_store = key_store.clone(); + let key_manager_state = state.into(); let payment_intent_fut = tokio::spawn( async move { m_db.update_payment_intent( + &key_manager_state, m_payment_data_payment_intent, storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields { amount: payment_data.payment_intent.amount, @@ -1320,10 +1327,13 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let m_customer_merchant_id = customer.merchant_id.to_owned(); let m_key_store = key_store.clone(); let m_updated_customer = updated_customer.clone(); - let m_db = state.clone().store; + let session_state = state.clone(); + let m_db = session_state.store.clone(); + let key_manager_state = state.into(); tokio::spawn( async move { m_db.update_customer_by_customer_id_merchant_id( + &key_manager_state, m_customer_customer_id, m_customer_merchant_id, customer, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 18dc2c5f39a..929f404eae9 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -6,7 +6,7 @@ use api_models::{ use async_trait::async_trait; use common_utils::{ ext_traits::{AsyncExt, Encode, ValueExt}, - types::MinorUnit, + types::{keymanager::Identifier, MinorUnit}, }; use diesel_models::{ephemeral_key, PaymentMethod}; use error_stack::{self, ResultExt}; @@ -32,7 +32,10 @@ use crate::{ utils as core_utils, }, db::StorageInterface, - routes::{app::ReqState, SessionState}, + routes::{ + app::{ReqState, SessionStateInfo}, + SessionState, + }, services, types::{ api::{self, PaymentIdTypeExt}, @@ -143,7 +146,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let customer_details = helpers::get_customer_details_from_request(request); let shipping_address = helpers::create_or_find_address_for_payment_by_request( - db, + state, request.shipping.as_ref(), None, merchant_id, @@ -155,7 +158,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( - db, + state, request.billing.as_ref(), None, merchant_id, @@ -168,7 +171,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let payment_method_billing_address = helpers::create_or_find_address_for_payment_by_request( - db, + state, request .payment_method_data .as_ref() @@ -286,7 +289,12 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await?; payment_intent = db - .insert_payment_intent(payment_intent_new, merchant_key_store, storage_scheme) + .insert_payment_intent( + &state.into(), + payment_intent_new, + merchant_key_store, + storage_scheme, + ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), @@ -475,7 +483,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -488,8 +496,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -638,12 +646,15 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let raw_customer_details = customer .map(|customer| CustomerData::try_from(customer.clone())) .transpose()?; + let session_state = state.session_state(); // Updation of Customer Details for the cases where both customer_id and specific customer // details are provided in Payment Create Request let customer_details = raw_customer_details .clone() - .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .async_map(|customer_details| { + create_encrypted_data(&session_state, key_store, customer_details) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -652,6 +663,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, storage::PaymentIntentUpdate::PaymentCreateUpdate { return_url: None, @@ -836,7 +848,9 @@ impl PaymentCreate { .as_ref() .async_map(|pm_info| async { decrypt::<serde_json::Value, masking::WithType>( + &state.into(), pm_info.payment_method_data.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.get_inner().peek(), ) .await @@ -983,7 +997,7 @@ impl PaymentCreate { #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] async fn make_payment_intent( - _state: &SessionState, + state: &SessionState, payment_id: &str, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, @@ -1057,7 +1071,7 @@ impl PaymentCreate { let billing_details = request .billing .clone() - .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1068,7 +1082,7 @@ impl PaymentCreate { let shipping_details = request .shipping .clone() - .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1093,7 +1107,7 @@ impl PaymentCreate { // Encrypting our Customer Details to be stored in Payment Intent let customer_details = raw_customer_details - .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .async_map(|customer_details| create_encrypted_data(state, key_store, customer_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index a3a8130a9f6..a83079a6a43 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -48,6 +48,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -79,7 +80,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -89,7 +90,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -99,7 +100,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -234,6 +235,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for Payme payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, intent_status_update, key_store, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index fc075f29799..808b2ae6181 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2,7 +2,10 @@ use std::collections::HashMap; use async_trait::async_trait; use common_enums::AuthorizationStatus; -use common_utils::{ext_traits::Encode, types::MinorUnit}; +use common_utils::{ + ext_traits::Encode, + types::{keymanager::KeyManagerState, MinorUnit}, +}; use error_stack::{report, ResultExt}; use futures::FutureExt; use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; @@ -265,7 +268,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu { async fn update_tracker<'b>( &'b self, - db: &'b SessionState, + state: &'b SessionState, _payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, router_data: types::RouterData< @@ -317,7 +320,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu }; //payment_attempt update if let Some(payment_attempt_update) = option_payment_attempt_update { - payment_data.payment_attempt = db + payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), @@ -329,9 +332,10 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu } // payment_intent update if let Some(payment_intent_update) = option_payment_intent_update { - payment_data.payment_intent = db + payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), payment_intent_update, key_store, @@ -370,7 +374,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu "missing authorization_id in incremental_authorization_details in payment_data", ), )?; - db.store + state + .store .update_authorization_by_merchant_id_authorization_id( router_data.merchant_id.clone(), authorization_id, @@ -380,7 +385,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed while updating authorization")?; //Fetch all the authorizations of the payment and send in incremental authorization response - let authorizations = db + let authorizations = state .store .find_all_authorizations_by_merchant_id_payment_id( &router_data.merchant_id, @@ -1255,9 +1260,11 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( let m_key_store = key_store.clone(); let m_payment_data_payment_intent = payment_data.payment_intent.clone(); let m_payment_intent_update = payment_intent_update.clone(); + let key_manager_state: KeyManagerState = state.into(); let payment_intent_fut = tokio::spawn( async move { m_db.update_payment_intent( + &key_manager_state, m_payment_data_payment_intent, m_payment_intent_update, &m_key_store, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 503a5c5f2bb..00f599d4095 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -13,7 +13,6 @@ use crate::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, PaymentData}, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -53,6 +52,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> let mut payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -89,7 +89,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> let amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -99,7 +99,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -109,7 +109,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -244,6 +244,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for Some(metadata) => state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, storage::PaymentIntentUpdate::MetadataUpdate { metadata, @@ -295,7 +296,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<payments::CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -308,8 +309,8 @@ where errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -358,6 +359,7 @@ where let all_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), &merchant_account.merchant_id, false, key_store, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index c4096c6ea5a..98befe122cc 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -12,7 +12,6 @@ use crate::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -51,6 +50,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -86,7 +86,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -96,7 +96,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -106,7 +106,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -268,7 +268,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -281,8 +281,8 @@ where errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 5f20ccdf277..fff096d9b4c 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; @@ -16,7 +16,6 @@ use crate::{ PaymentData, }, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -58,7 +57,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -71,8 +70,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -197,7 +196,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest payment_id, merchant_account, key_store, - &*state.store, + state, request, self, merchant_account.storage_scheme, @@ -214,7 +213,7 @@ async fn get_tracker_for_sync< payment_id: &api::PaymentIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - db: &dyn StorageInterface, + state: &SessionState, request: &api::PaymentsRetrieveRequest, operation: Op, storage_scheme: enums::MerchantStorageScheme, @@ -222,7 +221,7 @@ async fn get_tracker_for_sync< let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( - db, + state, payment_id, &merchant_account.merchant_id, key_store, @@ -238,7 +237,7 @@ async fn get_tracker_for_sync< amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id.clone(), @@ -247,7 +246,7 @@ async fn get_tracker_for_sync< ) .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), @@ -257,7 +256,7 @@ async fn get_tracker_for_sync< .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), @@ -267,7 +266,7 @@ async fn get_tracker_for_sync< .await?; payment_attempt.encoded_data.clone_from(&request.param); - + let db = &*state.store; let attempts = match request.expand_attempts { Some(true) => { Some(db @@ -510,18 +509,21 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for Payme } pub async fn get_payment_intent_payment_attempt( - db: &dyn StorageInterface, + state: &SessionState, payment_id: &api::PaymentIdType, merchant_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> { + let key_manager_state: KeyManagerState = state.into(); + let db = &*state.store; let get_pi_pa = || async { let (pi, pa); match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { pi = db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, id, merchant_id, key_store, @@ -547,6 +549,7 @@ pub async fn get_payment_intent_payment_attempt( .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, pa.payment_id.as_str(), merchant_id, key_store, @@ -560,6 +563,7 @@ pub async fn get_payment_intent_payment_attempt( .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, pa.payment_id.as_str(), merchant_id, key_store, @@ -578,6 +582,7 @@ pub async fn get_payment_intent_payment_attempt( pi = db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, pa.payment_id.as_str(), merchant_id, key_store, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 98006e574ca..f95ec0d0143 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -24,7 +24,6 @@ use crate::{ payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -64,6 +63,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -193,7 +193,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa } let shipping_address = helpers::create_or_update_address_for_payment_by_request( - db, + state, request.shipping.as_ref(), payment_intent.shipping_address_id.as_deref(), merchant_id, @@ -207,7 +207,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ) .await?; let billing_address = helpers::create_or_update_address_for_payment_by_request( - db, + state, request.billing.as_ref(), payment_intent.billing_address_id.as_deref(), merchant_id, @@ -222,7 +222,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await?; let payment_method_billing = helpers::create_or_update_address_for_payment_by_request( - db, + state, request .payment_method_data .as_ref() @@ -491,7 +491,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -504,8 +504,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -715,7 +715,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let billing_details = payment_data .address .get_payment_billing() - .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -724,7 +724,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let shipping_details = payment_data .address .get_shipping() - .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -741,6 +741,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields { amount: payment_data.amount.into(), diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 61a629df622..20c2e051b61 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -16,10 +16,7 @@ use crate::{ PaymentAddress, }, }, - routes::{ - app::{ReqState, StorageInterface}, - SessionState, - }, + routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, @@ -59,6 +56,7 @@ impl<F: Send + Clone> let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -179,7 +177,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAut #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, - db: &'b SessionState, + state: &'b SessionState, _req_state: ReqState, mut payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, @@ -224,7 +222,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAut connector_authorization_id: None, previously_authorized_amount: payment_data.payment_intent.amount, }; - let authorization = db + let authorization = state .store .insert_authorization(authorization_new.clone()) .await @@ -236,9 +234,10 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAut }) .attach_printable("failed while inserting new authorization")?; // Update authorization_count in payment_intent - payment_data.payment_intent = db + payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count: new_authorization_count, @@ -295,7 +294,7 @@ impl<F: Clone + Send> Domain<F, PaymentsIncrementalAuthorizationRequest> #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - _db: &dyn StorageInterface, + _state: &SessionState, _payment_data: &mut payments::PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index bf5ae5aa635..99cb6aaec68 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -469,6 +469,7 @@ where payment_data.payment_intent = db .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id: payment_data.payment_attempt.attempt_id.clone(), diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 0ff53c63b48..ff9f6ddbf3a 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -528,6 +528,7 @@ pub async fn refresh_cgraph_cache<'a>( let mut merchant_connector_accounts = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), &key_store.merchant_id, false, key_store, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b77bdb7515e..40163367139 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -8,7 +8,7 @@ use common_utils::{ id_type, pii, }; use error_stack::{report, ResultExt}; -use masking::{ExposeInterface, PeekInterface, Secret}; +use masking::{ExposeInterface, Secret}; use router_env::{instrument, metrics::add_attributes, tracing}; use super::helpers; @@ -214,7 +214,7 @@ where let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details - .async_map(|pm_card| create_encrypted_data(key_store, pm_card)) + .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -223,7 +223,7 @@ where let encrypted_payment_method_billing_address: Option< Encryptable<Secret<serde_json::Value>>, > = payment_method_billing_address - .async_map(|address| create_encrypted_data(key_store, address.clone())) + .async_map(|address| create_encrypted_data(state, key_store, address.clone())) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -310,7 +310,7 @@ where let pm_metadata = create_payment_method_metadata(None, connector_token)?; payment_methods::cards::create_payment_method( - db, + state, &payment_method_create_request, &customer_id, &resp.payment_method_id, @@ -407,7 +407,7 @@ where Err(err) => { if err.current_context().is_db_not_found() { payment_methods::cards::insert_payment_method( - db, + state, &resp, &payment_method_create_request.clone(), key_store, @@ -479,10 +479,8 @@ where ))? }; - let existing_pm_data = payment_methods::cards::get_card_details_without_locker_fallback( - &existing_pm, - key_store.key.peek(), - state, + let existing_pm_data = payment_methods::cards::get_card_details_without_locker_fallback(&existing_pm,state, + key_store, ) .await?; @@ -518,7 +516,7 @@ where let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = updated_pmd - .async_map(|pmd| create_encrypted_data(key_store, pmd)) + .async_map(|pmd| create_encrypted_data(state, key_store, pmd)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -601,7 +599,7 @@ where resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); payment_methods::cards::create_payment_method( - db, + state, &payment_method_create_request, &customer_id, &resp.payment_method_id, diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 3de8e505499..78ff9900f66 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -122,6 +122,7 @@ pub async fn initiate_payout_link( // Fetch customer let customer = db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &customer_id, &req.merchant_id, &key_store, @@ -263,10 +264,12 @@ pub async fn filter_payout_methods( key_store: &domain::MerchantKeyStore, payout: &hyperswitch_domain_models::payouts::payouts::Payouts, ) -> errors::RouterResult<Vec<link_utils::EnabledPaymentMethod>> { - let db: &dyn StorageInterface = &*state.store; + let db = &*state.store; + let key_manager_state = &state.into(); //Fetch all merchant connector accounts let all_mcas = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, &merchant_account.merchant_id, false, key_store, @@ -282,7 +285,7 @@ pub async fn filter_payout_methods( common_enums::ConnectorType::PayoutProcessor, ); let address = db - .find_address_by_address_id(&payout.address_id.clone(), key_store) + .find_address_by_address_id(key_manager_state, &payout.address_id.clone(), key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 4365519aecc..0ec3960b07d 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -732,6 +732,7 @@ pub async fn payouts_list_core( Ok(payout_attempt) => { match db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &payouts.customer_id, merchant_id, &key_store, @@ -822,7 +823,14 @@ pub async fn payouts_filtered_list_core( .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let data: Vec<api::PayoutCreateResponse> = join_all(list.into_iter().map(|(p, pa, c)| async { - match domain::Customer::convert_back(c, &key_store.key).await { + match domain::Customer::convert_back( + &(&state).into(), + c, + &key_store.key, + key_store.merchant_id.clone(), + ) + .await + { Ok(domain_cust) => Some((p, pa, domain_cust)), Err(err) => { logger::warn!( @@ -1084,6 +1092,7 @@ pub async fn create_recipient( { payout_data.customer_details = Some( db.update_customer_by_customer_id_merchant_id( + &state.into(), customer_id, merchant_id, customer, @@ -2184,7 +2193,7 @@ pub async fn payout_create_db_entries( // Get or create address let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( - db, + state, req.billing.as_ref(), None, merchant_id, @@ -2345,7 +2354,7 @@ pub async fn make_payout_data( .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( - db, + state, None, Some(&payouts.address_id.to_owned()), merchant_id, @@ -2358,6 +2367,7 @@ pub async fn make_payout_data( let customer_details = db .find_customer_optional_by_customer_id_merchant_id( + &state.into(), &payouts.customer_id.to_owned(), merchant_id, key_store, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 3ab17143202..6cda7b28433 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,13 +1,17 @@ -use api_models::{enums, payment_methods::Card, payouts}; +use api_models::{customers::CustomerRequestWithEmail, enums, payment_methods::Card, payouts}; use common_utils::{ + encryption::Encryption, errors::CustomResult, ext_traits::{AsyncExt, StringExt}, fp_utils, generate_customer_id_of_default_length, id_type, - types::MinorUnit, + types::{ + keymanager::{Identifier, KeyManagerState, ToEncryptable}, + MinorUnit, + }, }; -use diesel_models::encryption::Encryption; use error_stack::{report, ResultExt}; -use masking::{ExposeInterface, PeekInterface, Secret}; +use hyperswitch_domain_models::type_encryption::batch_encrypt; +use masking::{PeekInterface, Secret}; use router_env::logger; use super::PayoutData; @@ -233,6 +237,7 @@ pub async fn save_payout_data_to_locker( } _ => { let key = key_store.key.get_inner().peek(); + let key_manager_state: KeyManagerState = state.into(); let enc_data = async { serde_json::to_value(payout_method_data.to_owned()) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -242,7 +247,14 @@ pub async fn save_payout_data_to_locker( let secret: Secret<String> = Secret::new(v.to_string()); secret }) - .async_lift(|inner| domain_types::encrypt_optional(inner, key)) + .async_lift(|inner| { + domain_types::encrypt_optional( + &key_manager_state, + inner, + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + }) .await } .await @@ -453,7 +465,7 @@ pub async fn save_payout_data_to_locker( }); ( Some( - cards::create_encrypted_data(key_store, pm_data) + cards::create_encrypted_data(state, key_store, pm_data) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?, @@ -489,7 +501,7 @@ pub async fn save_payout_data_to_locker( if should_insert_in_pm_table { let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); cards::create_payment_method( - db, + state, &new_payment_method, &payout_attempt.customer_id, &payment_method_id, @@ -601,9 +613,11 @@ pub async fn get_or_create_customer_details( let merchant_id = &merchant_account.merchant_id; let key = key_store.key.get_inner().peek(); + let key_manager_state = &state.into(); match db .find_customer_optional_by_customer_id_merchant_id( + key_manager_state, &customer_id, merchant_id, key_store, @@ -614,21 +628,28 @@ pub async fn get_or_create_customer_details( { Some(customer) => Ok(Some(customer)), None => { + let encrypted_data = batch_encrypt( + &state.into(), + CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail { + name: customer_details.name.clone(), + email: customer_details.email.clone(), + phone: customer_details.phone.clone(), + }), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let encryptable_customer = + CustomerRequestWithEmail::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let customer = domain::Customer { customer_id, merchant_id: merchant_id.to_string(), - name: domain_types::encrypt_optional(customer_details.name.to_owned(), key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - email: domain_types::encrypt_optional( - customer_details.email.to_owned().map(|e| e.expose()), - key, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - phone: domain_types::encrypt_optional(customer_details.phone.to_owned(), key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: encryptable_customer.phone, description: None, phone_country_code: customer_details.phone_country_code.to_owned(), metadata: None, @@ -642,9 +663,14 @@ pub async fn get_or_create_customer_details( }; Ok(Some( - db.insert_customer(customer, key_store, merchant_account.storage_scheme) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, + db.insert_customer( + key_manager_state, + customer, + key_store, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?, )) } } diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 3434ac3e9c7..32e5ef308cf 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -15,7 +15,7 @@ use common_utils::{ crypto::{HmacSha256, SignMessage}, ext_traits::AsyncExt, generate_id, - types::{self as util_types, AmountConvertor}, + types::{self as util_types, keymanager::Identifier, AmountConvertor}, }; use error_stack::ResultExt; use helpers::PaymentAuthConnectorDataExt; @@ -110,7 +110,7 @@ pub async fn create_link_token( > = connector.connector.get_connector_integration(); let payment_intent = oss_helpers::verify_payment_intent_time_and_client_secret( - &*state.store, + &state, &merchant_account, &key_store, payload.client_secret, @@ -121,7 +121,7 @@ pub async fn create_link_token( .as_ref() .async_map(|pi| async { oss_helpers::get_address_by_id( - &*state.store, + &state, pi.billing_address_id.clone(), &key_store, &pi.payment_id, @@ -139,6 +139,7 @@ pub async fn create_link_token( let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &(&state).into(), merchant_account.merchant_id.as_str(), &selected_config.mca_id, &key_store, @@ -234,6 +235,7 @@ pub async fn exchange_token_core( let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &(&state).into(), merchant_account.merchant_id.as_str(), &config.mca_id, &key_store, @@ -294,6 +296,7 @@ async fn store_bank_details_in_payment_methods( let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payload.payment_id, &merchant_account.merchant_id, &key_store, @@ -326,7 +329,9 @@ async fn store_bank_details_in_payment_methods( for pm in payment_methods { if pm.payment_method == Some(enums::PaymentMethod::BankDebit) { let bank_details_pm_data = decrypt::<serde_json::Value, masking::WithType>( + &(&state).into(), pm.payment_method_data.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await @@ -433,10 +438,11 @@ async fn store_bank_details_in_payment_methods( ); let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); - let encrypted_data = cards::create_encrypted_data(&key_store, payment_method_data) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt customer details")?; + let encrypted_data = + cards::create_encrypted_data(&state, &key_store, payment_method_data) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt customer details")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: Some(encrypted_data.into()), @@ -446,7 +452,7 @@ async fn store_bank_details_in_payment_methods( } else { let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); let encrypted_data = - cards::create_encrypted_data(&key_store, Some(payment_method_data)) + cards::create_encrypted_data(&state, &key_store, Some(payment_method_data)) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?; @@ -701,14 +707,19 @@ pub async fn retrieve_payment_method_from_auth_service( let connector = PaymentAuthConnectorData::get_connector_by_name( auth_token.connector_details.connector.as_str(), )?; - + let key_manager_state = &state.into(); let merchant_account = db - .find_merchant_account_by_merchant_id(&payment_intent.merchant_id, key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &payment_intent.merchant_id, + key_store, + ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &payment_intent.merchant_id, &auth_token.connector_details.mca_id, key_store, @@ -770,7 +781,7 @@ pub async fn retrieve_payment_method_from_auth_service( } let address = oss_helpers::get_address_by_id( - &*state.store, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 5b74eefb9a4..374c37dc217 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -57,6 +57,7 @@ pub async fn refund_create_core( payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &req.payment_id, merchant_id, &key_store, @@ -415,6 +416,7 @@ pub async fn refund_retrieve_core( let payment_id = refund.payment_id.as_str(); payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), payment_id, merchant_id, &key_store, @@ -924,9 +926,11 @@ pub async fn refund_manual_update( state: SessionState, req: api_models::refunds::RefundManualUpdateRequest, ) -> RouterResponse<serde_json::Value> { + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &req.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -935,7 +939,7 @@ pub async fn refund_manual_update( .attach_printable("Error while fetching the key store by merchant_id")?; let merchant_account = state .store - .find_merchant_account_by_merchant_id(&req.merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; @@ -1125,6 +1129,7 @@ pub async fn sync_refund_with_gateway_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { + let key_manager_state = &state.into(); let refund_core = serde_json::from_value::<storage::RefundCoreWorkflow>(refund_tracker.tracking_data.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1138,6 +1143,7 @@ pub async fn sync_refund_with_gateway_workflow( let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -1145,7 +1151,11 @@ pub async fn sync_refund_with_gateway_workflow( let merchant_account = state .store - .find_merchant_account_by_merchant_id(&refund_core.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &refund_core.merchant_id, + &key_store, + ) .await?; let response = Box::pin(refund_retrieve_core( @@ -1220,17 +1230,22 @@ pub async fn trigger_refund_execute_workflow( refund_tracker.tracking_data ) })?; - + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db - .find_merchant_account_by_merchant_id(&refund_core.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &refund_core.merchant_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1245,7 +1260,11 @@ pub async fn trigger_refund_execute_workflow( match (&refund.sent_to_gateway, &refund.refund_status) { (false, enums::RefundStatus::Pending) => { let merchant_account = db - .find_merchant_account_by_merchant_id(&refund.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &refund.merchant_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1261,6 +1280,7 @@ pub async fn trigger_refund_execute_workflow( let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(state.into()), &payment_attempt.payment_id, &refund.merchant_id, &key_store, diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 5f10de56e47..b17217737be 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -120,7 +120,7 @@ pub async fn create_routing_config( .await?; helpers::validate_connectors_in_routing_config( - db, + &state, &key_store, &merchant_account.merchant_id, &profile_id, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index d99177aa555..707ed41d95a 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -15,6 +15,7 @@ use storage_impl::redis::cache; use crate::{ core::errors::{self, RouterResult}, db::StorageInterface, + routes::SessionState, types::{domain, storage}, utils::StringExt, }; @@ -186,7 +187,7 @@ pub async fn update_routing_algorithm( /// This will help make one of all configured algorithms to be in active state for a particular /// merchant pub async fn update_merchant_active_algorithm_ref( - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, config_key: cache::CacheKind<'_>, algorithm_id: routing_types::RoutingAlgorithmRef, @@ -218,8 +219,9 @@ pub async fn update_merchant_active_algorithm_ref( payment_link_config: None, pm_collect_link_config: None, }; - + let db = &*state.store; db.update_specific_fields_in_merchant( + &state.into(), &key_store.merchant_id, merchant_account_update, key_store, @@ -300,14 +302,16 @@ pub async fn update_business_profile_active_algorithm_ref( } pub async fn validate_connectors_in_routing_config( - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, merchant_id: &str, profile_id: &str, routing_algorithm: &routing_types::RoutingAlgorithm, ) -> RouterResult<()> { - let all_mcas = db + let all_mcas = &*state + .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_id, true, key_store, diff --git a/crates/router/src/core/surcharge_decision_config.rs b/crates/router/src/core/surcharge_decision_config.rs index b35d7c5ad28..55ea4ba16f8 100644 --- a/crates/router/src/core/surcharge_decision_config.rs +++ b/crates/router/src/core/surcharge_decision_config.rs @@ -91,7 +91,7 @@ pub async fn upsert_surcharge_decision_config( algo_id.update_surcharge_config_id(key.clone()); let config_key = cache::CacheKind::Surcharge(key.into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -128,7 +128,7 @@ pub async fn upsert_surcharge_decision_config( algo_id.update_surcharge_config_id(key.clone()); let config_key = cache::CacheKind::Surcharge(key.clone().into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -158,7 +158,7 @@ pub async fn delete_surcharge_decision_config( .unwrap_or_default(); algo_id.surcharge_config_algo_id = None; let config_key = cache::CacheKind::Surcharge(key.clone().into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 461ac855364..be33ccc69e1 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -4,6 +4,7 @@ use api_models::{ payments::RedirectionResponse, user::{self as user_api, InviteMultipleUserResponse}, }; +use common_utils::types::keymanager::Identifier; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; use diesel_models::{ @@ -1104,9 +1105,11 @@ pub async fn create_internal_user( state: SessionState, request: user_api::CreateInternalUserRequest, ) -> UserResponse<()> { + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, consts::user_role::INTERNAL_USER_MERCHANT_ID, &state.store.get_master_key().to_vec().into(), ) @@ -1122,6 +1125,7 @@ pub async fn create_internal_user( let internal_merchant = state .store .find_merchant_account_by_merchant_id( + key_manager_state, consts::user_role::INTERNAL_USER_MERCHANT_ID, &key_store, ) @@ -1176,7 +1180,7 @@ pub async fn switch_merchant_id( } let user = user_from_token.get_user_from_db(&state).await?; - + let key_manager_state = &(&state).into(); let role_info = roles::RoleInfo::from_role_id( &state, &user_from_token.role_id, @@ -1190,6 +1194,7 @@ pub async fn switch_merchant_id( let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, request.merchant_id.as_str(), &state.store.get_master_key().to_vec().into(), ) @@ -1204,7 +1209,11 @@ pub async fn switch_merchant_id( let org_id = state .store - .find_merchant_account_by_merchant_id(request.merchant_id.as_str(), &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + request.merchant_id.as_str(), + &key_store, + ) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1306,6 +1315,7 @@ pub async fn list_merchants_for_user( let merchant_accounts = state .store .list_multiple_merchant_accounts( + &(&state).into(), user_roles .iter() .map(|role| role.merchant_id.clone()) @@ -1852,7 +1862,9 @@ pub async fn update_totp( totp_secret: Some( // TODO: Impl conversion trait for User and move this there domain::types::encrypt::<String, masking::WithType>( + &(&state).into(), totp.get_secret_base32().into(), + Identifier::User(key_store.user_id.clone()), key_store.key.peek(), ) .await @@ -1918,7 +1930,10 @@ pub async fn transfer_user_key_store_keymanager( let db = &state.global_store; let key_stores = db - .get_all_user_key_store(&state.store.get_master_key().to_vec().into()) + .get_all_user_key_store( + &(&state).into(), + &state.store.get_master_key().to_vec().into(), + ) .await .change_context(UserErrors::InternalServerError)?; @@ -2056,10 +2071,12 @@ pub async fn create_user_authentication_method( ) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; - + let id = uuid::Uuid::new_v4().to_string(); let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( + &state, &req.auth_method, &user_auth_encryption_key, + id.clone(), ) .await?; @@ -2103,7 +2120,7 @@ pub async fn create_user_authentication_method( state .store .insert_user_authentication_method(UserAuthenticationMethodNew { - id: uuid::Uuid::new_v4().to_string(), + id, auth_id, owner_id: req.owner_id, owner_type: req.owner_type, @@ -2137,8 +2154,10 @@ pub async fn update_user_authentication_method( .attach_printable("Failed to decode DEK")?; let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( + &state, &req.auth_method, &user_auth_encryption_key, + req.id.clone(), ) .await?; @@ -2212,9 +2231,12 @@ pub async fn get_sso_auth_url( .await .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; - let open_id_private_config = - utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) - .await?; + let open_id_private_config = utils::user::decrypt_oidc_private_config( + &state, + user_authentication_method.private_config, + request.id.clone(), + ) + .await?; let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( user_authentication_method @@ -2264,9 +2286,12 @@ pub async fn sso_sign( .await .change_context(UserErrors::InternalServerError)?; - let open_id_private_config = - utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) - .await?; + let open_id_private_config = utils::user::decrypt_oidc_private_config( + &state, + user_authentication_method.private_config, + authentication_method_id, + ) + .await?; let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( user_authentication_method diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 36489846294..b279d852d40 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -613,6 +613,7 @@ pub async fn backfill_metadata( let key_store = state .store .get_merchant_key_store_by_merchant_id( + &state.into(), &user.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -713,6 +714,7 @@ pub async fn get_merchant_connector_account_by_name( state .store .find_merchant_connector_account_by_merchant_id_connector_name( + &state.into(), merchant_id, connector_name, key_store, diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs index e1ccb3b0335..b679753b56c 100644 --- a/crates/router/src/core/user/sample_data.rs +++ b/crates/router/src/core/user/sample_data.rs @@ -25,6 +25,7 @@ pub async fn generate_sample_data_for_user( let key_store = state .store .get_merchant_key_store_by_merchant_id( + &(&state).into(), &user_from_token.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -50,7 +51,7 @@ pub async fn generate_sample_data_for_user( state .store - .insert_payment_intents_batch_for_sample_data(payment_intents, &key_store) + .insert_payment_intents_batch_for_sample_data(&(&state).into(), payment_intents, &key_store) .await .switch()?; state @@ -74,10 +75,11 @@ pub async fn delete_sample_data_for_user( _req_state: ReqState, ) -> SampleDataApiResponse<()> { let merchant_id_del = user_from_token.merchant_id.as_str(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &user_from_token.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -87,7 +89,7 @@ pub async fn delete_sample_data_for_user( state .store - .delete_payment_intents_for_sample_data(merchant_id_del, &key_store) + .delete_payment_intents_for_sample_data(key_manager_state, merchant_id_del, &key_store) .await .switch()?; state diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index b6e71b2828f..65ac5688325 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -91,13 +91,19 @@ pub async fn get_verified_apple_domains_with_mid_mca_id( errors::ApiErrorResponse, > { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?; let verified_domains = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, merchant_id.as_str(), merchant_connector_id.as_str(), &key_store, diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs index bfbc1cb8b44..a59789b2802 100644 --- a/crates/router/src/core/verification/utils.rs +++ b/crates/router/src/core/verification/utils.rs @@ -15,9 +15,11 @@ pub async fn check_existence_and_add_domain_to_db( merchant_connector_id: String, domain_from_req: Vec<String>, ) -> CustomResult<Vec<String>, errors::ApiErrorResponse> { + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -27,6 +29,7 @@ pub async fn check_existence_and_add_domain_to_db( let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_id, &merchant_connector_id, &key_store, @@ -66,6 +69,7 @@ pub async fn check_existence_and_add_domain_to_db( state .store .update_merchant_connector_account( + key_manager_state, merchant_connector_account, updated_mca.into(), &key_store, diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 9eb74dc2df4..5c5346ce134 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -258,7 +258,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( Some(merchant_connector_account) => merchant_connector_account, None => { helper_utils::get_mca_from_object_reference_id( - &*state.clone().store, + &state, object_ref_id.clone(), &merchant_account, &connector_name, @@ -1675,6 +1675,7 @@ async fn fetch_optional_mca_and_connector( if connector_name_or_mca_id.starts_with("mca_") { let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &state.into(), &merchant_account.merchant_id, connector_name_or_mca_id, key_store, diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index c40b4ae8869..ed2b41dc64d 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -4,7 +4,7 @@ use api_models::{ webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent}, webhooks, }; -use common_utils::{ext_traits::Encode, request::RequestContent}; +use common_utils::{ext_traits::Encode, request::RequestContent, types::keymanager::Identifier}; use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::type_encryption::decrypt; @@ -87,6 +87,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( }; let request_content = get_outgoing_webhook_request( + &state, &merchant_account, outgoing_webhook, &business_profile, @@ -97,7 +98,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( .attach_printable("Failed to construct outgoing webhook request content")?; let event_metadata = storage::EventMetadata::foreign_from((&content, &primary_object_id)); - + let key_manager_state = &(&state).into(); let new_event = domain::Event { event_id: event_id.clone(), event_type, @@ -113,11 +114,13 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( initial_attempt_id: Some(event_id.clone()), request: Some( domain_types::encrypt( + key_manager_state, request_content .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to encode outgoing webhook request content") .map(Secret::new)?, + Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await @@ -131,7 +134,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( let event_insert_result = state .store - .insert_event(new_event, merchant_key_store) + .insert_event(key_manager_state, new_event, merchant_key_store) .await; let event = match event_insert_result { @@ -552,6 +555,7 @@ fn get_webhook_url_from_business_profile( } pub(crate) async fn get_outgoing_webhook_request( + state: &SessionState, merchant_account: &domain::MerchantAccount, outgoing_webhook: api::OutgoingWebhook, business_profile: &diesel_models::business_profile::BusinessProfile, @@ -559,6 +563,7 @@ pub(crate) async fn get_outgoing_webhook_request( ) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> { #[inline] async fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>( + state: &SessionState, outgoing_webhook: api::OutgoingWebhook, business_profile: &diesel_models::business_profile::BusinessProfile, key_store: &domain::MerchantKeyStore, @@ -571,9 +576,11 @@ pub(crate) async fn get_outgoing_webhook_request( let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook); let payment_response_hash_key = business_profile.payment_response_hash_key.clone(); let custom_headers = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), business_profile .outgoing_webhook_custom_http_headers .clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.get_inner().peek(), ) .await @@ -614,6 +621,7 @@ pub(crate) async fn get_outgoing_webhook_request( #[cfg(feature = "stripe")] Some(api_models::enums::Connector::Stripe) => { get_outgoing_webhook_request_inner::<stripe_webhooks::StripeOutgoingWebhook>( + state, outgoing_webhook, business_profile, key_store, @@ -622,6 +630,7 @@ pub(crate) async fn get_outgoing_webhook_request( } _ => { get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>( + state, outgoing_webhook, business_profile, key_store, @@ -645,7 +654,7 @@ async fn update_event_if_client_error( error_message: String, ) -> CustomResult<domain::Event, errors::WebhooksFlowError> { let is_webhook_notified = false; - + let key_manager_state = &(&state).into(); let response_to_store = OutgoingWebhookResponseContent { body: None, headers: None, @@ -657,12 +666,14 @@ async fn update_event_if_client_error( is_webhook_notified, response: Some( domain_types::encrypt( + key_manager_state, response_to_store .encode_to_string_of_json() .change_context( errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, ) .map(Secret::new)?, + Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await @@ -674,6 +685,7 @@ async fn update_event_if_client_error( state .store .update_event_by_merchant_id_event_id( + key_manager_state, merchant_id, event_id, event_update, @@ -733,7 +745,7 @@ async fn update_event_in_storage( ) -> CustomResult<domain::Event, errors::WebhooksFlowError> { let status_code = response.status(); let is_webhook_notified = status_code.is_success(); - + let key_manager_state = &(&state).into(); let response_headers = response .headers() .iter() @@ -772,12 +784,14 @@ async fn update_event_in_storage( is_webhook_notified, response: Some( domain_types::encrypt( + key_manager_state, response_to_store .encode_to_string_of_json() .change_context( errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, ) .map(Secret::new)?, + Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await @@ -788,6 +802,7 @@ async fn update_event_in_storage( state .store .update_event_by_merchant_id_event_id( + key_manager_state, merchant_id, event_id, event_update, diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs index 2a16ccce0b4..19118ad639a 100644 --- a/crates/router/src/core/webhooks/webhook_events.rs +++ b/crates/router/src/core/webhooks/webhook_events.rs @@ -28,7 +28,7 @@ pub async fn list_initial_delivery_attempts( api::webhook_events::EventListConstraintsInternal::foreign_try_from(constraints)?; let store = state.store.as_ref(); - + let key_manager_state = &(&state).into(); let (account, key_store) = determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?; @@ -36,14 +36,14 @@ pub async fn list_initial_delivery_attempts( api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => { match account { MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => store - .list_initial_events_by_merchant_id_primary_object_id( + .list_initial_events_by_merchant_id_primary_object_id(key_manager_state, &merchant_account.merchant_id, &object_id, &key_store, ) .await, MerchantAccountOrBusinessProfile::BusinessProfile(business_profile) => store - .list_initial_events_by_profile_id_primary_object_id( + .list_initial_events_by_profile_id_primary_object_id(key_manager_state, &business_profile.profile_id, &object_id, &key_store, @@ -73,7 +73,7 @@ pub async fn list_initial_delivery_attempts( match account { MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => store - .list_initial_events_by_merchant_id_constraints( + .list_initial_events_by_merchant_id_constraints(key_manager_state, &merchant_account.merchant_id, created_after, created_before, @@ -83,7 +83,7 @@ pub async fn list_initial_delivery_attempts( ) .await, MerchantAccountOrBusinessProfile::BusinessProfile(business_profile) => store - .list_initial_events_by_profile_id_constraints( + .list_initial_events_by_profile_id_constraints(key_manager_state, &business_profile.profile_id, created_after, created_before, @@ -116,11 +116,12 @@ pub async fn list_delivery_attempts( let (account, key_store) = determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?; - + let key_manager_state = &(&state).into(); let events = match account { MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => { store .list_events_by_merchant_id_initial_attempt_id( + key_manager_state, &merchant_account.merchant_id, &initial_attempt_id, &key_store, @@ -130,6 +131,7 @@ pub async fn list_delivery_attempts( MerchantAccountOrBusinessProfile::BusinessProfile(business_profile) => { store .list_events_by_profile_id_initial_attempt_id( + key_manager_state, &business_profile.profile_id, &initial_attempt_id, &key_store, @@ -162,12 +164,17 @@ pub async fn retry_delivery_attempt( event_id: String, ) -> RouterResponse<api::webhook_events::EventRetrieveResponse> { let store = state.store.as_ref(); - + let key_manager_state = &(&state).into(); let (account, key_store) = determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?; let event_to_retry = store - .find_event_by_merchant_id_event_id(&key_store.merchant_id, &event_id, &key_store) + .find_event_by_merchant_id_event_id( + key_manager_state, + &key_store.merchant_id, + &event_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::EventNotFound)?; @@ -216,7 +223,7 @@ pub async fn retry_delivery_attempt( }; let event = store - .insert_event(new_event, &key_store) + .insert_event(key_manager_state, new_event, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert event")?; @@ -245,7 +252,12 @@ pub async fn retry_delivery_attempt( .await; let updated_event = store - .find_event_by_merchant_id_event_id(&key_store.merchant_id, &new_event_id, &key_store) + .find_event_by_merchant_id_event_id( + key_manager_state, + &key_store.merchant_id, + &new_event_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::EventNotFound)?; @@ -259,8 +271,10 @@ async fn determine_identifier_and_get_key_store( merchant_id_or_profile_id: String, ) -> errors::RouterResult<(MerchantAccountOrBusinessProfile, domain::MerchantKeyStore)> { let store = state.store.as_ref(); + let key_manager_state = &(&state).into(); match store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id_or_profile_id, &store.get_master_key().to_vec().into(), ) @@ -271,7 +285,11 @@ async fn determine_identifier_and_get_key_store( // Find a merchant account having `merchant_id` = `merchant_id_or_profile_id`. Ok(key_store) => { let merchant_account = store - .find_merchant_account_by_merchant_id(&merchant_id_or_profile_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &merchant_id_or_profile_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -301,6 +319,7 @@ async fn determine_identifier_and_get_key_store( let key_store = store .get_merchant_key_store_by_merchant_id( + key_manager_state, &business_profile.merchant_id, &store.get_master_key().to_vec().into(), ) diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index f210019b4da..04a8f673a94 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -1,4 +1,4 @@ -use common_utils::id_type; +use common_utils::{id_type, types::keymanager::KeyManagerState}; use diesel_models::{address::AddressUpdateInternal, enums::MerchantStorageScheme}; use error_stack::ResultExt; @@ -22,6 +22,7 @@ where { async fn update_address( &self, + state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, @@ -29,6 +30,7 @@ where async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: String, @@ -38,12 +40,14 @@ where async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn insert_address_for_payments( &self, + state: &KeyManagerState, payment_id: &str, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, @@ -52,12 +56,14 @@ where async fn insert_address_for_customers( &self, + state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, merchant_id: &str, payment_id: &str, address_id: &str, @@ -67,6 +73,7 @@ where async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address: storage_types::AddressUpdate, @@ -76,7 +83,7 @@ where #[cfg(not(feature = "kv_store"))] mod storage { - use common_utils::{ext_traits::AsyncExt, id_type}; + use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; @@ -98,6 +105,7 @@ mod storage { #[instrument(skip_all)] async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -107,7 +115,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -117,6 +129,7 @@ mod storage { #[instrument(skip_all)] async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, merchant_id: &str, payment_id: &str, address_id: &str, @@ -134,7 +147,7 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) }) @@ -144,6 +157,7 @@ mod storage { #[instrument(skip_all)] async fn update_address( &self, + state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, @@ -154,7 +168,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -164,6 +182,7 @@ mod storage { #[instrument(skip_all)] async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, _payment_id: String, @@ -180,7 +199,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -190,6 +213,7 @@ mod storage { #[instrument(skip_all)] async fn insert_address_for_payments( &self, + state: &KeyManagerState, _payment_id: &str, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, @@ -205,7 +229,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -215,6 +243,7 @@ mod storage { #[instrument(skip_all)] async fn insert_address_for_customers( &self, + state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -228,7 +257,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -238,6 +271,7 @@ mod storage { #[instrument(skip_all)] async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address: storage_types::AddressUpdate, @@ -257,7 +291,7 @@ mod storage { for address in addresses.into_iter() { output.push( address - .convert(key_store.key.get_inner()) + .convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -271,7 +305,7 @@ mod storage { #[cfg(feature = "kv_store")] mod storage { - use common_utils::{ext_traits::AsyncExt, id_type}; + use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::{enums::MerchantStorageScheme, AddressUpdateInternal}; use error_stack::{report, ResultExt}; use redis_interface::HsetnxReply; @@ -299,6 +333,7 @@ mod storage { #[instrument(skip_all)] async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -308,7 +343,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -318,6 +357,7 @@ mod storage { #[instrument(skip_all)] async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, merchant_id: &str, payment_id: &str, address_id: &str, @@ -362,7 +402,11 @@ mod storage { } }?; address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -370,6 +414,7 @@ mod storage { #[instrument(skip_all)] async fn update_address( &self, + state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, @@ -380,7 +425,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -390,6 +439,7 @@ mod storage { #[instrument(skip_all)] async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, payment_id: String, @@ -420,7 +470,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -457,7 +511,11 @@ mod storage { .change_context(errors::StorageError::KVError)?; updated_address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -467,6 +525,7 @@ mod storage { #[instrument(skip_all)] async fn insert_address_for_payments( &self, + state: &KeyManagerState, payment_id: &str, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, @@ -493,7 +552,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -553,7 +616,11 @@ mod storage { } .into()), Ok(HsetnxReply::KeySet) => Ok(created_address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?), Err(er) => Err(er).change_context(errors::StorageError::KVError), @@ -565,6 +632,7 @@ mod storage { #[instrument(skip_all)] async fn insert_address_for_customers( &self, + state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -578,7 +646,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -588,6 +660,7 @@ mod storage { #[instrument(skip_all)] async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address: storage_types::AddressUpdate, @@ -607,7 +680,11 @@ mod storage { for address in addresses.into_iter() { output.push( address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -623,6 +700,7 @@ mod storage { impl AddressInterface for MockDb { async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -635,7 +713,11 @@ impl AddressInterface for MockDb { { Some(address) => address .clone() - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => { @@ -648,6 +730,7 @@ impl AddressInterface for MockDb { async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, _merchant_id: &str, _payment_id: &str, address_id: &str, @@ -663,7 +746,11 @@ impl AddressInterface for MockDb { { Some(address) => address .clone() - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => { @@ -676,6 +763,7 @@ impl AddressInterface for MockDb { async fn update_address( &self, + state: &KeyManagerState, address_id: String, address_update: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, @@ -694,7 +782,11 @@ impl AddressInterface for MockDb { }); match updated_addr { Some(address_updated) => address_updated - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( @@ -706,6 +798,7 @@ impl AddressInterface for MockDb { async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, _payment_id: String, @@ -726,7 +819,11 @@ impl AddressInterface for MockDb { }); match updated_addr { Some(address_updated) => address_updated - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( @@ -738,6 +835,7 @@ impl AddressInterface for MockDb { async fn insert_address_for_payments( &self, + state: &KeyManagerState, _payment_id: &str, address_new: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, @@ -752,13 +850,18 @@ impl AddressInterface for MockDb { addresses.push(address.clone()); address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } async fn insert_address_for_customers( &self, + state: &KeyManagerState, address_new: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -771,13 +874,18 @@ impl AddressInterface for MockDb { addresses.push(address.clone()); address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address_update: storage_types::AddressUpdate, @@ -801,7 +909,11 @@ impl AddressInterface for MockDb { match updated_addr { Some(address) => { let address: domain::Address = address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; Ok(vec![address]) diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs index cad3d2969fe..1bfda658521 100644 --- a/crates/router/src/db/customers.rs +++ b/crates/router/src/db/customers.rs @@ -1,4 +1,4 @@ -use common_utils::{ext_traits::AsyncExt, id_type}; +use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use futures::future::try_join_all; use router_env::{instrument, tracing}; @@ -29,14 +29,17 @@ where async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, errors::StorageError>; + #[allow(clippy::too_many_arguments)] async fn update_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: String, customer: domain::Customer, @@ -47,6 +50,7 @@ where async fn find_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -55,12 +59,14 @@ where async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError>; async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -69,7 +75,7 @@ where #[cfg(feature = "kv_store")] mod storage { - use common_utils::{ext_traits::AsyncExt, id_type}; + use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::kv; use error_stack::{report, ResultExt}; use futures::future::try_join_all; @@ -103,6 +109,7 @@ mod storage { // check customer not found in kv and fallback to db async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -149,9 +156,13 @@ mod storage { let maybe_result = maybe_customer .async_map(|c| async { - c.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + c.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; @@ -167,6 +178,7 @@ mod storage { #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: String, customer: domain::Customer, @@ -236,7 +248,11 @@ mod storage { }; updated_object? - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -244,6 +260,7 @@ mod storage { #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -287,7 +304,11 @@ mod storage { }?; let result: domain::Customer = customer - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; //.await @@ -303,6 +324,7 @@ mod storage { #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { @@ -316,7 +338,11 @@ mod storage { let customers = try_join_all(encrypted_customers.into_iter().map( |encrypted_customer| async { encrypted_customer - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }, @@ -329,6 +355,7 @@ mod storage { #[instrument(skip_all)] async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -394,7 +421,11 @@ mod storage { }?; create_customer - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -419,7 +450,7 @@ mod storage { #[cfg(not(feature = "kv_store"))] mod storage { - use common_utils::{ext_traits::AsyncExt, id_type}; + use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use futures::future::try_join_all; use masking::PeekInterface; @@ -447,6 +478,7 @@ mod storage { #[instrument(skip_all)] async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -462,7 +494,7 @@ mod storage { .await .map_err(|error| report!(errors::StorageError::from(error)))? .async_map(|c| async { - c.convert(key_store.key.get_inner()) + c.convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) }) @@ -483,6 +515,7 @@ mod storage { #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: String, _customer: domain::Customer, @@ -494,13 +527,13 @@ mod storage { storage_types::Customer::update_by_customer_id_merchant_id( &conn, customer_id, - merchant_id, + merchant_id.clone(), customer_update.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { - c.convert(key_store.key.get_inner()) + c.convert(state, key_store.key.get_inner(), merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -510,6 +543,7 @@ mod storage { #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -525,7 +559,7 @@ mod storage { .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { - c.convert(key_store.key.get_inner()) + c.convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) }) @@ -541,6 +575,7 @@ mod storage { #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { @@ -554,7 +589,7 @@ mod storage { let customers = try_join_all(encrypted_customers.into_iter().map( |encrypted_customer| async { encrypted_customer - .convert(key_store.key.get_inner()) + .convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) }, @@ -567,6 +602,7 @@ mod storage { #[instrument(skip_all)] async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -580,9 +616,13 @@ mod storage { .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { - c.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + c.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -610,6 +650,7 @@ impl CustomerInterface for MockDb { #[allow(clippy::panic)] async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -624,9 +665,13 @@ impl CustomerInterface for MockDb { .cloned(); customer .async_map(|c| async { - c.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + c.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await .transpose() @@ -634,6 +679,7 @@ impl CustomerInterface for MockDb { async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { @@ -646,7 +692,11 @@ impl CustomerInterface for MockDb { .map(|customer| async { customer .to_owned() - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }), @@ -659,6 +709,7 @@ impl CustomerInterface for MockDb { #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, + _state: &KeyManagerState, _customer_id: id_type::CustomerId, _merchant_id: String, _customer: domain::Customer, @@ -672,6 +723,7 @@ impl CustomerInterface for MockDb { async fn find_customer_by_customer_id_merchant_id( &self, + _state: &KeyManagerState, _customer_id: &id_type::CustomerId, _merchant_id: &str, _key_store: &domain::MerchantKeyStore, @@ -684,6 +736,7 @@ impl CustomerInterface for MockDb { #[allow(clippy::panic)] async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -697,7 +750,11 @@ impl CustomerInterface for MockDb { customers.push(customer.clone()); customer - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index aba11f95988..2fd8a09f173 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -1,4 +1,4 @@ -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; @@ -23,12 +23,14 @@ where { async fn insert_event( &self, + state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn find_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -36,13 +38,16 @@ where async fn list_initial_events_by_merchant_id_primary_object_id( &self, + state: &KeyManagerState, merchant_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; + #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_merchant_id_constraints( &self, + state: &KeyManagerState, merchant_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -53,6 +58,7 @@ where async fn list_events_by_merchant_id_initial_attempt_id( &self, + state: &KeyManagerState, merchant_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -60,13 +66,16 @@ where async fn list_initial_events_by_profile_id_primary_object_id( &self, + state: &KeyManagerState, profile_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; + #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_profile_id_constraints( &self, + state: &KeyManagerState, profile_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -77,6 +86,7 @@ where async fn list_events_by_profile_id_initial_attempt_id( &self, + state: &KeyManagerState, profile_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -84,6 +94,7 @@ where async fn update_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, event: domain::EventUpdate, @@ -96,6 +107,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn insert_event( &self, + state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { @@ -107,7 +119,11 @@ impl EventInterface for Store { .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -115,6 +131,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn find_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -123,7 +140,11 @@ impl EventInterface for Store { storage::Event::find_by_merchant_id_event_id(&conn, merchant_id, event_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -131,6 +152,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_primary_object_id( &self, + state: &KeyManagerState, merchant_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -148,7 +170,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -161,6 +187,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_constraints( &self, + state: &KeyManagerState, merchant_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -184,7 +211,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -197,6 +228,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_events_by_merchant_id_initial_attempt_id( &self, + state: &KeyManagerState, merchant_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -214,7 +246,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -227,6 +263,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_initial_events_by_profile_id_primary_object_id( &self, + state: &KeyManagerState, profile_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -244,7 +281,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -257,6 +298,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_initial_events_by_profile_id_constraints( &self, + state: &KeyManagerState, profile_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -280,7 +322,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -293,6 +339,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_events_by_profile_id_initial_attempt_id( &self, + state: &KeyManagerState, profile_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -306,7 +353,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -319,6 +370,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn update_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, event: domain::EventUpdate, @@ -328,7 +380,11 @@ impl EventInterface for Store { storage::Event::update_by_merchant_id_event_id(&conn, merchant_id, event_id, event.into()) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -338,6 +394,7 @@ impl EventInterface for Store { impl EventInterface for MockDb { async fn insert_event( &self, + state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { @@ -350,13 +407,18 @@ impl EventInterface for MockDb { locked_events.push(stored_event.clone()); stored_event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -370,7 +432,11 @@ impl EventInterface for MockDb { .cloned() .async_map(|event| async { event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -386,6 +452,7 @@ impl EventInterface for MockDb { async fn list_initial_events_by_merchant_id_primary_object_id( &self, + state: &KeyManagerState, merchant_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -405,7 +472,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -416,6 +487,7 @@ impl EventInterface for MockDb { async fn list_initial_events_by_merchant_id_constraints( &self, + state: &KeyManagerState, merchant_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -470,7 +542,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -481,6 +557,7 @@ impl EventInterface for MockDb { async fn list_events_by_merchant_id_initial_attempt_id( &self, + state: &KeyManagerState, merchant_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -498,7 +575,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -509,6 +590,7 @@ impl EventInterface for MockDb { async fn list_initial_events_by_profile_id_primary_object_id( &self, + state: &KeyManagerState, profile_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -528,7 +610,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -539,6 +625,7 @@ impl EventInterface for MockDb { async fn list_initial_events_by_profile_id_constraints( &self, + state: &KeyManagerState, profile_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -593,7 +680,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -604,6 +695,7 @@ impl EventInterface for MockDb { async fn list_events_by_profile_id_initial_attempt_id( &self, + state: &KeyManagerState, profile_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -621,7 +713,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -632,6 +728,7 @@ impl EventInterface for MockDb { async fn update_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, event: domain::EventUpdate, @@ -657,7 +754,11 @@ impl EventInterface for MockDb { event_to_update .clone() - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -665,6 +766,9 @@ impl EventInterface for MockDb { #[cfg(test)] mod tests { + use std::sync::Arc; + + use common_utils::types::keymanager::Identifier; use diesel_models::{enums, events::EventMetadata}; use time::macros::datetime; @@ -673,6 +777,10 @@ mod tests { events::EventInterface, merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, }, + routes::{ + self, + app::{settings::Settings, StorageImpl}, + }, services, types::domain, }; @@ -685,17 +793,31 @@ mod tests { .await .expect("Failed to create Mock store"); let event_id = "test_event_id"; + let (tx, _) = tokio::sync::oneshot::channel(); + let app_state = Box::pin(routes::AppState::with_storage( + Settings::default(), + StorageImpl::PostgresqlTest, + tx, + Box::new(services::MockApiClient), + )) + .await; + let state = &Arc::new(app_state) + .get_session_state("public", || {}) + .unwrap(); let merchant_id = "merchant1"; let business_profile_id = "profile1"; let payment_id = "test_payment_id"; - + let key_manager_state = &state.into(); let master_key = mockdb.get_master_key(); mockdb .insert_merchant_key_store( + key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.into(), key: domain::types::encrypt( + key_manager_state, services::generate_aes256_key().unwrap().to_vec().into(), + Identifier::Merchant(merchant_id.to_string()), master_key, ) .await @@ -707,12 +829,17 @@ mod tests { .await .unwrap(); let merchant_key_store = mockdb - .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &master_key.to_vec().into(), + ) .await .unwrap(); let event1 = mockdb .insert_event( + key_manager_state, domain::Event { event_id: event_id.into(), event_type: enums::EventType::PaymentSucceeded, @@ -742,6 +869,7 @@ mod tests { let updated_event = mockdb .update_event_by_merchant_id_event_id( + key_manager_state, merchant_id, event_id, domain::EventUpdate::UpdateResponse { diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index ce0821c6322..ed2357c1a1c 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use common_enums::enums::MerchantStorageScheme; -use common_utils::{errors::CustomResult, id_type, pii}; +use common_utils::{errors::CustomResult, id_type, pii, types::keymanager::KeyManagerState}; use diesel_models::{ enums, enums::ProcessTrackerStatus, @@ -102,27 +102,30 @@ impl KafkaStore { impl AddressInterface for KafkaStore { async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store - .find_address_by_address_id(address_id, key_store) + .find_address_by_address_id(state, address_id, key_store) .await } async fn update_address( &self, + state: &KeyManagerState, address_id: String, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store - .update_address(address_id, address, key_store) + .update_address(state, address_id, address, key_store) .await } async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: String, @@ -130,24 +133,33 @@ impl AddressInterface for KafkaStore { storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store - .update_address_for_payments(this, address, payment_id, key_store, storage_scheme) + .update_address_for_payments( + state, + this, + address, + payment_id, + key_store, + storage_scheme, + ) .await } async fn insert_address_for_payments( &self, + state: &KeyManagerState, payment_id: &str, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store - .insert_address_for_payments(payment_id, address, key_store, storage_scheme) + .insert_address_for_payments(state, payment_id, address, key_store, storage_scheme) .await } async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, merchant_id: &str, payment_id: &str, address_id: &str, @@ -156,6 +168,7 @@ impl AddressInterface for KafkaStore { ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .find_address_by_merchant_id_payment_id_address_id( + state, merchant_id, payment_id, address_id, @@ -167,23 +180,31 @@ impl AddressInterface for KafkaStore { async fn insert_address_for_customers( &self, + state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store - .insert_address_for_customers(address, key_store) + .insert_address_for_customers(state, address, key_store) .await } async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { self.diesel_store - .update_address_by_merchant_id_customer_id(customer_id, merchant_id, address, key_store) + .update_address_by_merchant_id_customer_id( + state, + customer_id, + merchant_id, + address, + key_store, + ) .await } } @@ -332,6 +353,7 @@ impl CustomerInterface for KafkaStore { async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -339,6 +361,7 @@ impl CustomerInterface for KafkaStore { ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { self.diesel_store .find_customer_optional_by_customer_id_merchant_id( + state, customer_id, merchant_id, key_store, @@ -349,6 +372,7 @@ impl CustomerInterface for KafkaStore { async fn update_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: String, customer: domain::Customer, @@ -358,6 +382,7 @@ impl CustomerInterface for KafkaStore { ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .update_customer_by_customer_id_merchant_id( + state, customer_id, merchant_id, customer, @@ -370,16 +395,18 @@ impl CustomerInterface for KafkaStore { async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { self.diesel_store - .list_customers_by_merchant_id(merchant_id, key_store) + .list_customers_by_merchant_id(state, merchant_id, key_store) .await } async fn find_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -387,6 +414,7 @@ impl CustomerInterface for KafkaStore { ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .find_customer_by_customer_id_merchant_id( + state, customer_id, merchant_id, key_store, @@ -397,12 +425,13 @@ impl CustomerInterface for KafkaStore { async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store - .insert_customer(customer_data, key_store, storage_scheme) + .insert_customer(state, customer_data, key_store, storage_scheme) .await } } @@ -519,33 +548,37 @@ impl EphemeralKeyInterface for KafkaStore { impl EventInterface for KafkaStore { async fn insert_event( &self, + state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store - .insert_event(event, merchant_key_store) + .insert_event(state, event, merchant_key_store) .await } async fn find_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store - .find_event_by_merchant_id_event_id(merchant_id, event_id, merchant_key_store) + .find_event_by_merchant_id_event_id(state, merchant_id, event_id, merchant_key_store) .await } async fn list_initial_events_by_merchant_id_primary_object_id( &self, + state: &KeyManagerState, merchant_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_merchant_id_primary_object_id( + state, merchant_id, primary_object_id, merchant_key_store, @@ -555,6 +588,7 @@ impl EventInterface for KafkaStore { async fn list_initial_events_by_merchant_id_constraints( &self, + state: &KeyManagerState, merchant_id: &str, created_after: Option<PrimitiveDateTime>, created_before: Option<PrimitiveDateTime>, @@ -564,6 +598,7 @@ impl EventInterface for KafkaStore { ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_merchant_id_constraints( + state, merchant_id, created_after, created_before, @@ -576,12 +611,14 @@ impl EventInterface for KafkaStore { async fn list_events_by_merchant_id_initial_attempt_id( &self, + state: &KeyManagerState, merchant_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_events_by_merchant_id_initial_attempt_id( + state, merchant_id, initial_attempt_id, merchant_key_store, @@ -591,12 +628,14 @@ impl EventInterface for KafkaStore { async fn list_initial_events_by_profile_id_primary_object_id( &self, + state: &KeyManagerState, profile_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_profile_id_primary_object_id( + state, profile_id, primary_object_id, merchant_key_store, @@ -606,6 +645,7 @@ impl EventInterface for KafkaStore { async fn list_initial_events_by_profile_id_constraints( &self, + state: &KeyManagerState, profile_id: &str, created_after: Option<PrimitiveDateTime>, created_before: Option<PrimitiveDateTime>, @@ -615,6 +655,7 @@ impl EventInterface for KafkaStore { ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_profile_id_constraints( + state, profile_id, created_after, created_before, @@ -627,12 +668,14 @@ impl EventInterface for KafkaStore { async fn list_events_by_profile_id_initial_attempt_id( &self, + state: &KeyManagerState, profile_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_events_by_profile_id_initial_attempt_id( + state, profile_id, initial_attempt_id, merchant_key_store, @@ -642,13 +685,20 @@ impl EventInterface for KafkaStore { async fn update_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store - .update_event_by_merchant_id_event_id(merchant_id, event_id, event, merchant_key_store) + .update_event_by_merchant_id_event_id( + state, + merchant_id, + event_id, + event, + merchant_key_store, + ) .await } } @@ -790,43 +840,47 @@ impl PaymentLinkInterface for KafkaStore { impl MerchantAccountInterface for KafkaStore { async fn insert_merchant( &self, + state: &KeyManagerState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store - .insert_merchant(merchant_account, key_store) + .insert_merchant(state, merchant_account, key_store) .await } async fn find_merchant_account_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store - .find_merchant_account_by_merchant_id(merchant_id, key_store) + .find_merchant_account_by_merchant_id(state, merchant_id, key_store) .await } async fn update_merchant( &self, + state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store - .update_merchant(this, merchant_account, key_store) + .update_merchant(state, this, merchant_account, key_store) .await } async fn update_specific_fields_in_merchant( &self, + state: &KeyManagerState, merchant_id: &str, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store - .update_specific_fields_in_merchant(merchant_id, merchant_account, key_store) + .update_specific_fields_in_merchant(state, merchant_id, merchant_account, key_store) .await } @@ -841,20 +895,22 @@ impl MerchantAccountInterface for KafkaStore { async fn find_merchant_account_by_publishable_key( &self, + state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError> { self.diesel_store - .find_merchant_account_by_publishable_key(publishable_key) + .find_merchant_account_by_publishable_key(state, publishable_key) .await } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, + state: &KeyManagerState, organization_id: &str, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store - .list_merchant_accounts_by_organization_id(organization_id) + .list_merchant_accounts_by_organization_id(state, organization_id) .await } @@ -870,10 +926,11 @@ impl MerchantAccountInterface for KafkaStore { #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store - .list_multiple_merchant_accounts(merchant_ids) + .list_multiple_merchant_accounts(state, merchant_ids) .await } } @@ -957,12 +1014,14 @@ impl MerchantConnectorAccountInterface for KafkaStore { } async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, + state: &KeyManagerState, merchant_id: &str, connector: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_label( + state, merchant_id, connector, key_store, @@ -972,12 +1031,14 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, + state: &KeyManagerState, merchant_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_name( + state, merchant_id, connector_name, key_store, @@ -987,12 +1048,14 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn find_merchant_connector_account_by_profile_id_connector_name( &self, + state: &KeyManagerState, profile_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_profile_id_connector_name( + state, profile_id, connector_name, key_store, @@ -1002,22 +1065,25 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn insert_merchant_connector_account( &self, + state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store - .insert_merchant_connector_account(t, key_store) + .insert_merchant_connector_account(state, t, key_store) .await } async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_connector_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + state, merchant_id, merchant_connector_id, key_store, @@ -1027,12 +1093,14 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, + state: &KeyManagerState, merchant_id: &str, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + state, merchant_id, get_disabled, key_store, @@ -1042,12 +1110,13 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn update_merchant_connector_account( &self, + state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store - .update_merchant_connector_account(this, merchant_connector_account, key_store) + .update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } @@ -1326,6 +1395,7 @@ impl PaymentAttemptInterface for KafkaStore { impl PaymentIntentInterface for KafkaStore { async fn update_payment_intent( &self, + state: &KeyManagerState, this: storage::PaymentIntent, payment_intent: storage::PaymentIntentUpdate, key_store: &domain::MerchantKeyStore, @@ -1333,7 +1403,13 @@ impl PaymentIntentInterface for KafkaStore { ) -> CustomResult<storage::PaymentIntent, errors::DataStorageError> { let intent = self .diesel_store - .update_payment_intent(this.clone(), payment_intent, key_store, storage_scheme) + .update_payment_intent( + state, + this.clone(), + payment_intent, + key_store, + storage_scheme, + ) .await?; if let Err(er) = self @@ -1349,6 +1425,7 @@ impl PaymentIntentInterface for KafkaStore { async fn insert_payment_intent( &self, + state: &KeyManagerState, new: storage::PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -1356,7 +1433,7 @@ impl PaymentIntentInterface for KafkaStore { logger::debug!("Inserting PaymentIntent Via KafkaStore"); let intent = self .diesel_store - .insert_payment_intent(new, key_store, storage_scheme) + .insert_payment_intent(state, new, key_store, storage_scheme) .await?; if let Err(er) = self @@ -1372,6 +1449,7 @@ impl PaymentIntentInterface for KafkaStore { async fn find_payment_intent_by_payment_id_merchant_id( &self, + state: &KeyManagerState, payment_id: &str, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -1379,6 +1457,7 @@ impl PaymentIntentInterface for KafkaStore { ) -> CustomResult<storage::PaymentIntent, errors::DataStorageError> { self.diesel_store .find_payment_intent_by_payment_id_merchant_id( + state, payment_id, merchant_id, key_store, @@ -1390,19 +1469,27 @@ impl PaymentIntentInterface for KafkaStore { #[cfg(feature = "olap")] async fn filter_payment_intent_by_constraints( &self, + state: &KeyManagerState, merchant_id: &str, filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> { self.diesel_store - .filter_payment_intent_by_constraints(merchant_id, filters, key_store, storage_scheme) + .filter_payment_intent_by_constraints( + state, + merchant_id, + filters, + key_store, + storage_scheme, + ) .await } #[cfg(feature = "olap")] async fn filter_payment_intents_by_time_range_constraints( &self, + state: &KeyManagerState, merchant_id: &str, time_range: &api_models::payments::TimeRange, key_store: &domain::MerchantKeyStore, @@ -1410,6 +1497,7 @@ impl PaymentIntentInterface for KafkaStore { ) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> { self.diesel_store .filter_payment_intents_by_time_range_constraints( + state, merchant_id, time_range, key_store, @@ -1421,6 +1509,7 @@ impl PaymentIntentInterface for KafkaStore { #[cfg(feature = "olap")] async fn get_filtered_payment_intents_attempt( &self, + state: &KeyManagerState, merchant_id: &str, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, @@ -1434,6 +1523,7 @@ impl PaymentIntentInterface for KafkaStore { > { self.diesel_store .get_filtered_payment_intents_attempt( + state, merchant_id, constraints, key_store, @@ -2059,21 +2149,23 @@ impl RefundInterface for KafkaStore { impl MerchantKeyStoreInterface for KafkaStore { async fn insert_merchant_key_store( &self, + state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.diesel_store - .insert_merchant_key_store(merchant_key_store, key) + .insert_merchant_key_store(state, merchant_key_store, key) .await } async fn get_merchant_key_store_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.diesel_store - .get_merchant_key_store_by_merchant_id(merchant_id, key) + .get_merchant_key_store_by_merchant_id(state, merchant_id, key) .await } @@ -2089,18 +2181,20 @@ impl MerchantKeyStoreInterface for KafkaStore { #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { self.diesel_store - .list_multiple_key_stores(merchant_ids, key) + .list_multiple_key_stores(state, merchant_ids, key) .await } async fn get_all_key_stores( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { - self.diesel_store.get_all_key_stores(key).await + self.diesel_store.get_all_key_stores(state, key).await } } @@ -2592,6 +2686,7 @@ impl DashboardMetadataInterface for KafkaStore { impl BatchSampleDataInterface for KafkaStore { async fn insert_payment_intents_batch_for_sample_data( &self, + state: &KeyManagerState, batch: Vec<hyperswitch_domain_models::payments::PaymentIntent>, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult< @@ -2600,7 +2695,7 @@ impl BatchSampleDataInterface for KafkaStore { > { let payment_intents_list = self .diesel_store - .insert_payment_intents_batch_for_sample_data(batch, key_store) + .insert_payment_intents_batch_for_sample_data(state, batch, key_store) .await?; for payment_intent in payment_intents_list.iter() { @@ -2654,6 +2749,7 @@ impl BatchSampleDataInterface for KafkaStore { async fn delete_payment_intents_for_sample_data( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult< @@ -2662,7 +2758,7 @@ impl BatchSampleDataInterface for KafkaStore { > { let payment_intents_list = self .diesel_store - .delete_payment_intents_for_sample_data(merchant_id, key_store) + .delete_payment_intents_for_sample_data(state, merchant_id, key_store) .await?; for payment_intent in payment_intents_list.iter() { @@ -2947,29 +3043,32 @@ impl GenericLinkInterface for KafkaStore { impl UserKeyStoreInterface for KafkaStore { async fn insert_user_key_store( &self, + state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.diesel_store - .insert_user_key_store(user_key_store, key) + .insert_user_key_store(state, user_key_store, key) .await } async fn get_user_key_store_by_user_id( &self, + state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.diesel_store - .get_user_key_store_by_user_id(user_id, key) + .get_user_key_store_by_user_id(state, user_id, key) .await } async fn get_all_user_key_store( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { - self.diesel_store.get_all_user_key_store(key).await + self.diesel_store.get_all_user_key_store(state, key).await } } diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index ff3830b2381..eadf00c872c 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -1,7 +1,7 @@ #[cfg(feature = "olap")] use std::collections::HashMap; -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use diesel_models::MerchantAccountUpdateInternal; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; @@ -31,12 +31,14 @@ where { async fn insert_merchant( &self, + state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn find_merchant_account_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; @@ -48,6 +50,7 @@ where async fn update_merchant( &self, + state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, @@ -55,6 +58,7 @@ where async fn update_specific_fields_in_merchant( &self, + state: &KeyManagerState, merchant_id: &str, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, @@ -62,12 +66,14 @@ where async fn find_merchant_account_by_publishable_key( &self, + state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError>; #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, + state: &KeyManagerState, organization_id: &str, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; @@ -79,6 +85,7 @@ where #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; } @@ -88,6 +95,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn insert_merchant( &self, + state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { @@ -99,7 +107,11 @@ impl MerchantAccountInterface for Store { .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -107,6 +119,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { @@ -121,7 +134,11 @@ impl MerchantAccountInterface for Store { { fetch_func() .await? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_id.to_string(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -130,7 +147,11 @@ impl MerchantAccountInterface for Store { { cache::get_or_populate_in_memory(self, merchant_id, fetch_func, &ACCOUNTS_CACHE) .await? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -139,6 +160,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn update_merchant( &self, + state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, @@ -157,7 +179,11 @@ impl MerchantAccountInterface for Store { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -165,6 +191,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, + state: &KeyManagerState, merchant_id: &str, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, @@ -183,7 +210,11 @@ impl MerchantAccountInterface for Store { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -191,6 +222,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, + state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError> { let fetch_by_pub_key_func = || async { @@ -219,6 +251,7 @@ impl MerchantAccountInterface for Store { } let key_store = self .get_merchant_key_store_by_merchant_id( + state, &merchant_account.merchant_id, &self.get_master_key().to_vec().into(), ) @@ -226,7 +259,11 @@ impl MerchantAccountInterface for Store { Ok(authentication::AuthenticationData { merchant_account: merchant_account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, @@ -238,6 +275,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, + state: &KeyManagerState, organization_id: &str, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { use futures::future::try_join_all; @@ -253,6 +291,7 @@ impl MerchantAccountInterface for Store { let merchant_key_stores = try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| { self.get_merchant_key_store_by_merchant_id( + state, &merchant_account.merchant_id, &db_master_key, ) @@ -265,7 +304,11 @@ impl MerchantAccountInterface for Store { .zip(merchant_key_stores.iter()) .map(|(merchant_account, key_store)| async { merchant_account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }), @@ -314,6 +357,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -327,6 +371,7 @@ impl MerchantAccountInterface for Store { let merchant_key_stores = self .list_multiple_key_stores( + state, encrypted_merchant_accounts .iter() .map(|merchant_account| &merchant_account.merchant_id) @@ -351,7 +396,11 @@ impl MerchantAccountInterface for Store { )), )?; merchant_account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }, @@ -399,6 +448,7 @@ impl MerchantAccountInterface for MockDb { #[allow(clippy::panic)] async fn insert_merchant( &self, + state: &KeyManagerState, mut merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { @@ -412,7 +462,11 @@ impl MerchantAccountInterface for MockDb { accounts.push(account.clone()); account - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -420,6 +474,7 @@ impl MerchantAccountInterface for MockDb { #[allow(clippy::panic)] async fn find_merchant_account_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { @@ -429,9 +484,13 @@ impl MerchantAccountInterface for MockDb { .find(|account| account.merchant_id == merchant_id) .cloned() .async_map(|a| async { - a.convert(merchant_key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + a.convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; @@ -445,6 +504,7 @@ impl MerchantAccountInterface for MockDb { async fn update_merchant( &self, + _state: &KeyManagerState, _this: domain::MerchantAccount, _merchant_account: storage::MerchantAccountUpdate, _merchant_key_store: &domain::MerchantKeyStore, @@ -455,6 +515,7 @@ impl MerchantAccountInterface for MockDb { async fn update_specific_fields_in_merchant( &self, + _state: &KeyManagerState, _merchant_id: &str, _merchant_account: storage::MerchantAccountUpdate, _merchant_key_store: &domain::MerchantKeyStore, @@ -465,6 +526,7 @@ impl MerchantAccountInterface for MockDb { async fn find_merchant_account_by_publishable_key( &self, + _state: &KeyManagerState, _publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError> { // [#172]: Implement function for `MockDb` @@ -489,6 +551,7 @@ impl MerchantAccountInterface for MockDb { #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, + _state: &KeyManagerState, _organization_id: &str, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { Err(errors::StorageError::MockDbError)? @@ -497,6 +560,7 @@ impl MerchantAccountInterface for MockDb { #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, + _state: &KeyManagerState, _merchant_ids: Vec<String>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { Err(errors::StorageError::MockDbError)? diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index b9becb90dca..078980f9184 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,6 +1,9 @@ use async_bb8_diesel::AsyncConnection; -use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode}; -use diesel_models::encryption::Encryption; +use common_utils::{ + encryption::Encryption, + ext_traits::{AsyncExt, ByteSliceExt, Encode}, + types::keymanager::KeyManagerState, +}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] @@ -121,6 +124,7 @@ where { async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, + state: &KeyManagerState, merchant_id: &str, connector_label: &str, key_store: &domain::MerchantKeyStore, @@ -128,6 +132,7 @@ where async fn find_merchant_connector_account_by_profile_id_connector_name( &self, + state: &KeyManagerState, profile_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -135,6 +140,7 @@ where async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, + state: &KeyManagerState, merchant_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -142,12 +148,14 @@ where async fn insert_merchant_connector_account( &self, + state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_connector_id: &str, key_store: &domain::MerchantKeyStore, @@ -155,6 +163,7 @@ where async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, + state: &KeyManagerState, merchant_id: &str, get_disabled: bool, key_store: &domain::MerchantKeyStore, @@ -162,6 +171,7 @@ where async fn update_merchant_connector_account( &self, + state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, @@ -187,6 +197,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, + state: &KeyManagerState, merchant_id: &str, connector_label: &str, key_store: &domain::MerchantKeyStore, @@ -206,7 +217,7 @@ impl MerchantConnectorAccountInterface for Store { { find_call() .await? - .convert(key_store.key.get_inner()) + .convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DeserializationFailed) } @@ -221,9 +232,13 @@ impl MerchantConnectorAccountInterface for Store { ) .await .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -232,6 +247,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, + state: &KeyManagerState, profile_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -251,7 +267,11 @@ impl MerchantConnectorAccountInterface for Store { { find_call() .await? - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DeserializationFailed) } @@ -266,9 +286,13 @@ impl MerchantConnectorAccountInterface for Store { ) .await .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -277,6 +301,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, + state: &KeyManagerState, merchant_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -293,9 +318,13 @@ impl MerchantConnectorAccountInterface for Store { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError)?, + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) @@ -306,6 +335,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_connector_id: &str, key_store: &domain::MerchantKeyStore, @@ -325,7 +355,11 @@ impl MerchantConnectorAccountInterface for Store { { find_call() .await? - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -339,7 +373,11 @@ impl MerchantConnectorAccountInterface for Store { &cache::ACCOUNTS_CACHE, ) .await? - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -348,6 +386,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, + state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { @@ -359,9 +398,13 @@ impl MerchantConnectorAccountInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -369,6 +412,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, + state: &KeyManagerState, merchant_id: &str, get_disabled: bool, key_store: &domain::MerchantKeyStore, @@ -381,9 +425,13 @@ impl MerchantConnectorAccountInterface for Store { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError)?, + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) @@ -492,6 +540,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn update_merchant_connector_account( &self, + state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, @@ -516,9 +565,13 @@ impl MerchantConnectorAccountInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await }; @@ -629,6 +682,7 @@ impl MerchantConnectorAccountInterface for MockDb { } async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, + state: &KeyManagerState, merchant_id: &str, connector: &str, key_store: &domain::MerchantKeyStore, @@ -645,7 +699,11 @@ impl MerchantConnectorAccountInterface for MockDb { .cloned() .async_map(|account| async { account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -663,6 +721,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, + state: &KeyManagerState, merchant_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -681,7 +740,11 @@ impl MerchantConnectorAccountInterface for MockDb { for account in accounts.into_iter() { output.push( account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -691,6 +754,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn find_merchant_connector_account_by_profile_id_connector_name( &self, + state: &KeyManagerState, profile_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -709,7 +773,11 @@ impl MerchantConnectorAccountInterface for MockDb { match maybe_mca { Some(mca) => mca .to_owned() - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( @@ -721,6 +789,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_connector_id: &str, key_store: &domain::MerchantKeyStore, @@ -737,7 +806,11 @@ impl MerchantConnectorAccountInterface for MockDb { .cloned() .async_map(|account| async { account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -755,6 +828,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn insert_merchant_connector_account( &self, + state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { @@ -788,13 +862,18 @@ impl MerchantConnectorAccountInterface for MockDb { }; accounts.push(account.clone()); account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, + state: &KeyManagerState, merchant_id: &str, get_disabled: bool, key_store: &domain::MerchantKeyStore, @@ -818,7 +897,11 @@ impl MerchantConnectorAccountInterface for MockDb { for account in accounts.into_iter() { output.push( account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -828,6 +911,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn update_merchant_connector_account( &self, + state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, @@ -846,7 +930,11 @@ impl MerchantConnectorAccountInterface for MockDb { }) .async_map(|account| async { account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -890,8 +978,10 @@ impl MerchantConnectorAccountInterface for MockDb { #[cfg(feature = "accounts_cache")] #[cfg(test)] mod merchant_connector_account_cache_tests { + use std::sync::Arc; + use api_models::enums::CountryAlpha2; - use common_utils::date_time; + use common_utils::{date_time, types::keymanager::Identifier}; use diesel_models::enums::ConnectorType; use error_stack::ResultExt; use masking::PeekInterface; @@ -901,6 +991,7 @@ mod merchant_connector_account_cache_tests { pub_sub::PubSubInterface, }; use time::macros::datetime; + use tokio::sync::oneshot; use crate::{ core::errors, @@ -908,6 +999,10 @@ mod merchant_connector_account_cache_tests { merchant_connector_account::MerchantConnectorAccountInterface, merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, }, + routes::{ + self, + app::{settings::Settings, StorageImpl}, + }, services, types::{ domain::{self, behaviour::Conversion}, @@ -918,6 +1013,19 @@ mod merchant_connector_account_cache_tests { #[allow(clippy::unwrap_used)] #[tokio::test] async fn test_connector_profile_id_cache() { + let conf = Settings::new().unwrap(); + let tx: oneshot::Sender<()> = oneshot::channel().0; + + let app_state = Box::pin(routes::AppState::with_storage( + conf, + StorageImpl::PostgresqlTest, + tx, + Box::new(services::MockApiClient), + )) + .await; + let state = &Arc::new(app_state) + .get_session_state("public", || {}) + .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) .await @@ -934,12 +1042,15 @@ mod merchant_connector_account_cache_tests { let connector_label = "stripe_USA"; let merchant_connector_id = "simple_merchant_connector_id"; let profile_id = "pro_max_ultra"; - + let key_manager_state = &state.into(); db.insert_merchant_key_store( + key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.into(), key: domain::types::encrypt( + key_manager_state, services::generate_aes256_key().unwrap().to_vec().into(), + Identifier::Merchant(merchant_id.to_string()), master_key, ) .await @@ -952,7 +1063,11 @@ mod merchant_connector_account_cache_tests { .unwrap(); let merchant_key = db - .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &master_key.to_vec().into(), + ) .await .unwrap(); @@ -961,7 +1076,9 @@ mod merchant_connector_account_cache_tests { merchant_id: merchant_id.to_string(), connector_name: "stripe".to_string(), connector_account_details: domain::types::encrypt( + key_manager_state, serde_json::Value::default().into(), + Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await @@ -986,7 +1103,9 @@ mod merchant_connector_account_cache_tests { status: common_enums::ConnectorStatus::Inactive, connector_wallets_details: Some( domain::types::encrypt( + key_manager_state, serde_json::Value::default().into(), + Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await @@ -995,13 +1114,14 @@ mod merchant_connector_account_cache_tests { additional_merchant_data: None, }; - db.insert_merchant_connector_account(mca.clone(), &merchant_key) + db.insert_merchant_connector_account(key_manager_state, mca.clone(), &merchant_key) .await .unwrap(); let find_call = || async { Conversion::convert( db.find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, profile_id, &mca.connector_name, &merchant_key, diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 42a862e2d3d..1cc12796bc6 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -1,3 +1,4 @@ +use common_utils::types::keymanager::KeyManagerState; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; @@ -19,12 +20,14 @@ use crate::{ pub trait MerchantKeyStoreInterface { async fn insert_merchant_key_store( &self, + state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; async fn get_merchant_key_store_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; @@ -37,12 +40,14 @@ pub trait MerchantKeyStoreInterface { #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; async fn get_all_key_stores( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; } @@ -52,10 +57,12 @@ impl MerchantKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_merchant_key_store( &self, + state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; + let merchant_id = merchant_key_store.merchant_id.clone(); merchant_key_store .construct_new() .await @@ -63,7 +70,7 @@ impl MerchantKeyStoreInterface for Store { .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(key) + .convert(state, key, merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -71,6 +78,7 @@ impl MerchantKeyStoreInterface for Store { #[instrument(skip_all)] async fn get_merchant_key_store_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { @@ -89,7 +97,7 @@ impl MerchantKeyStoreInterface for Store { { fetch_func() .await? - .convert(key) + .convert(state, key, merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } @@ -104,7 +112,7 @@ impl MerchantKeyStoreInterface for Store { &ACCOUNTS_CACHE, ) .await? - .convert(key) + .convert(state, key, merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } @@ -146,6 +154,7 @@ impl MerchantKeyStoreInterface for Store { #[instrument(skip_all)] async fn list_multiple_key_stores( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { @@ -161,8 +170,9 @@ impl MerchantKeyStoreInterface for Store { }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + let merchant_id = key_store.merchant_id.clone(); key_store - .convert(key) + .convert(state, key, merchant_id) .await .change_context(errors::StorageError::DecryptionError) })) @@ -171,6 +181,7 @@ impl MerchantKeyStoreInterface for Store { async fn get_all_key_stores( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -181,8 +192,9 @@ impl MerchantKeyStoreInterface for Store { }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + let merchant_id = key_store.merchant_id.clone(); key_store - .convert(key) + .convert(state, key, merchant_id) .await .change_context(errors::StorageError::DecryptionError) })) @@ -194,6 +206,7 @@ impl MerchantKeyStoreInterface for Store { impl MerchantKeyStoreInterface for MockDb { async fn insert_merchant_key_store( &self, + state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { @@ -213,15 +226,16 @@ impl MerchantKeyStoreInterface for MockDb { .await .change_context(errors::StorageError::MockDbError)?; locked_merchant_key_store.push(merchant_key.clone()); - + let merchant_id = merchant_key.merchant_id.clone(); merchant_key - .convert(key) + .convert(state, key, merchant_id) .await .change_context(errors::StorageError::DecryptionError) } async fn get_merchant_key_store_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { @@ -234,7 +248,7 @@ impl MerchantKeyStoreInterface for MockDb { .ok_or(errors::StorageError::ValueNotFound(String::from( "merchant_key_store", )))? - .convert(key) + .convert(state, key, merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } @@ -258,6 +272,7 @@ impl MerchantKeyStoreInterface for MockDb { #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { @@ -269,7 +284,7 @@ impl MerchantKeyStoreInterface for MockDb { .map(|merchant_key| async { merchant_key .to_owned() - .convert(key) + .convert(state, key, merchant_key.merchant_id.clone()) .await .change_context(errors::StorageError::DecryptionError) }), @@ -278,6 +293,7 @@ impl MerchantKeyStoreInterface for MockDb { } async fn get_all_key_stores( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; @@ -285,7 +301,7 @@ impl MerchantKeyStoreInterface for MockDb { futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { merchant_key .to_owned() - .convert(key) + .convert(state, key, merchant_key.merchant_id.clone()) .await .change_context(errors::StorageError::DecryptionError) })) @@ -295,30 +311,54 @@ impl MerchantKeyStoreInterface for MockDb { #[cfg(test)] mod tests { + use std::sync::Arc; + + use common_utils::types::keymanager::Identifier; use time::macros::datetime; + use tokio::sync::oneshot; use crate::{ db::{merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb}, + routes::{ + self, + app::{settings::Settings, StorageImpl}, + }, services, - types::domain::{self}, + types::domain, }; - #[allow(clippy::unwrap_used)] + #[allow(clippy::unwrap_used, clippy::expect_used)] #[tokio::test] async fn test_mock_db_merchant_key_store_interface() { + let conf = Settings::new().expect("invalid settings"); + let tx: oneshot::Sender<()> = oneshot::channel().0; + let app_state = Box::pin(routes::AppState::with_storage( + conf, + StorageImpl::PostgresqlTest, + tx, + Box::new(services::MockApiClient), + )) + .await; + let state = &Arc::new(app_state) + .get_session_state("public", || {}) + .unwrap(); #[allow(clippy::expect_used)] let mock_db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create mock DB"); let master_key = mock_db.get_master_key(); let merchant_id = "merchant1"; - + let identifier = Identifier::Merchant(merchant_id.to_string()); + let key_manager_state = &state.into(); let merchant_key1 = mock_db .insert_merchant_key_store( + key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.into(), key: domain::types::encrypt( + key_manager_state, services::generate_aes256_key().unwrap().to_vec().into(), + identifier.clone(), master_key, ) .await @@ -331,7 +371,11 @@ mod tests { .unwrap(); let found_merchant_key1 = mock_db - .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &master_key.to_vec().into(), + ) .await .unwrap(); @@ -340,10 +384,13 @@ mod tests { let insert_duplicate_merchant_key1_result = mock_db .insert_merchant_key_store( + key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.into(), key: domain::types::encrypt( + key_manager_state, services::generate_aes256_key().unwrap().to_vec().into(), + identifier.clone(), master_key, ) .await @@ -356,12 +403,20 @@ mod tests { assert!(insert_duplicate_merchant_key1_result.is_err()); let find_non_existent_merchant_key_result = mock_db - .get_merchant_key_store_by_merchant_id("non_existent", &master_key.to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + "non_existent", + &master_key.to_vec().into(), + ) .await; assert!(find_non_existent_merchant_key_result.is_err()); let find_merchant_key_with_incorrect_master_key_result = mock_db - .get_merchant_key_store_by_merchant_id(merchant_id, &vec![0; 32].into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &vec![0; 32].into(), + ) .await; assert!(find_merchant_key_with_incorrect_master_key_result.is_err()); } diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rs index 5a23666c7b1..cabf62b850e 100644 --- a/crates/router/src/db/user/sample_data.rs +++ b/crates/router/src/db/user/sample_data.rs @@ -1,3 +1,4 @@ +use common_utils::types::keymanager::KeyManagerState; use diesel_models::{ errors::DatabaseError, query::user::sample_data as sample_data_queries, @@ -20,6 +21,7 @@ use crate::{connection::pg_connection_write, core::errors::CustomResult, service pub trait BatchSampleDataInterface { async fn insert_payment_intents_batch_for_sample_data( &self, + state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; @@ -36,6 +38,7 @@ pub trait BatchSampleDataInterface { async fn delete_payment_intents_for_sample_data( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; @@ -55,6 +58,7 @@ pub trait BatchSampleDataInterface { impl BatchSampleDataInterface for Store { async fn insert_payment_intents_batch_for_sample_data( &self, + state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { @@ -68,13 +72,17 @@ impl BatchSampleDataInterface for Store { .change_context(StorageError::EncryptionError) })) .await?; - sample_data_queries::insert_payment_intents(&conn, new_intents) .await .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { - PaymentIntent::convert_back(payment_intent, key_store.key.get_inner()) + PaymentIntent::convert_back( + state, + payment_intent, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? @@ -111,6 +119,7 @@ impl BatchSampleDataInterface for Store { async fn delete_payment_intents_for_sample_data( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { @@ -122,7 +131,12 @@ impl BatchSampleDataInterface for Store { .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { - PaymentIntent::convert_back(payment_intent, key_store.key.get_inner()) + PaymentIntent::convert_back( + state, + payment_intent, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? @@ -162,6 +176,7 @@ impl BatchSampleDataInterface for Store { impl BatchSampleDataInterface for storage_impl::MockDb { async fn insert_payment_intents_batch_for_sample_data( &self, + _state: &KeyManagerState, _batch: Vec<PaymentIntent>, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { @@ -184,6 +199,7 @@ impl BatchSampleDataInterface for storage_impl::MockDb { async fn delete_payment_intents_for_sample_data( &self, + _state: &KeyManagerState, _merchant_id: &str, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs index c7e48037e96..e7dbe531c65 100644 --- a/crates/router/src/db/user_key_store.rs +++ b/crates/router/src/db/user_key_store.rs @@ -1,4 +1,4 @@ -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; @@ -18,18 +18,21 @@ use crate::{ pub trait UserKeyStoreInterface { async fn insert_user_key_store( &self, + state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_user_key_store_by_user_id( &self, + state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_all_user_key_store( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>; } @@ -39,10 +42,12 @@ impl UserKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_user_key_store( &self, + state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; + let user_id = user_key_store.user_id.clone(); user_key_store .construct_new() .await @@ -50,7 +55,7 @@ impl UserKeyStoreInterface for Store { .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(key) + .convert(state, key, user_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -58,6 +63,7 @@ impl UserKeyStoreInterface for Store { #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, + state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { @@ -66,13 +72,14 @@ impl UserKeyStoreInterface for Store { diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(key) + .convert(state, key, user_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -84,8 +91,9 @@ impl UserKeyStoreInterface for Store { }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + let user_id = key_store.user_id.clone(); key_store - .convert(key) + .convert(state, key, user_id) .await .change_context(errors::StorageError::DecryptionError) })) @@ -98,6 +106,7 @@ impl UserKeyStoreInterface for MockDb { #[instrument(skip_all)] async fn insert_user_key_store( &self, + state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { @@ -117,23 +126,25 @@ impl UserKeyStoreInterface for MockDb { .await .change_context(errors::StorageError::MockDbError)?; locked_user_key_store.push(user_key_store.clone()); - + let user_id = user_key_store.user_id.clone(); user_key_store - .convert(key) + .convert(state, key, user_id) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let user_key_store = self.user_key_store.lock().await; futures::future::try_join_all(user_key_store.iter().map(|user_key| async { + let user_id = user_key.user_id.clone(); user_key .to_owned() - .convert(key) + .convert(state, key, user_id) .await .change_context(errors::StorageError::DecryptionError) })) @@ -143,6 +154,7 @@ impl UserKeyStoreInterface for MockDb { #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, + state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { @@ -156,7 +168,7 @@ impl UserKeyStoreInterface for MockDb { "No user_key_store is found for user_id={}", user_id )))? - .convert(key) + .convert(state, key, user_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 38000f7b664..6405a3b8479 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -193,7 +193,11 @@ pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> Applicatio let api_client = Box::new( services::ProxyClient::new( conf.proxy.clone(), - services::proxy_bypass_urls(&conf.locker, &conf.proxy.bypass_proxy_urls), + services::proxy_bypass_urls( + conf.key_manager.get_inner(), + &conf.locker, + &conf.proxy.bypass_proxy_urls, + ), ) .map_err(|error| { errors::ApplicationError::ApiClientError(error.current_context().clone()) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0d7d042f7af..b733e76289e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -110,6 +110,7 @@ pub trait SessionStateInfo { fn event_handler(&self) -> EventsHandler; fn get_request_id(&self) -> Option<String>; fn add_request_id(&mut self, request_id: RequestId); + fn session_state(&self) -> SessionState; } impl SessionStateInfo for SessionState { @@ -130,6 +131,9 @@ impl SessionStateInfo for SessionState { self.store.add_request_id(request_id.to_string()); self.request_id.replace(request_id); } + fn session_state(&self) -> SessionState { + self.clone() + } } #[derive(Clone)] pub struct AppState { diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 003cd71c00d..25df0ef6434 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -40,7 +40,7 @@ pub async fn create_payment_method_api( json_payload.into_inner(), |state, auth, req, _| async move { Box::pin(cards::get_client_secret_or_add_payment_method( - state, + &state, req, &auth.merchant_account, &auth.key_store, @@ -88,9 +88,11 @@ async fn get_merchant_account( state: &SessionState, merchant_id: &str, ) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> { + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -99,7 +101,7 @@ async fn get_merchant_account( let merchant_account = state .store - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok((key_store, merchant_account)) @@ -530,7 +532,7 @@ pub async fn default_payment_method_set_api( payload, |state, auth: auth::AuthenticationData, default_payment_method, _| async move { cards::set_default_payment_method( - &*state.clone().store, + &state, auth.merchant_account.merchant_id, auth.key_store, customer_id, diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs index aabbd637ae7..d8100e8d341 100644 --- a/crates/router/src/routes/recon.rs +++ b/crates/router/src/routes/recon.rs @@ -85,15 +85,17 @@ pub async fn send_recon_request( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)? .merchant_id; + let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, 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) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id.as_str(), &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -130,7 +132,12 @@ pub async fn send_recon_request( }; let response = db - .update_merchant(merchant_account, updated_merchant_account, &key_store) + .update_merchant( + key_manager_state, + merchant_account, + updated_merchant_account, + &key_store, + ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { @@ -162,6 +169,7 @@ pub async fn recon_merchant_account_update( let key_store = db .get_merchant_key_store_by_merchant_id( + &(&state).into(), &req.merchant_id, &db.get_master_key().to_vec().into(), ) @@ -169,7 +177,7 @@ pub async fn recon_merchant_account_update( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(&(&state).into(), merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -178,7 +186,12 @@ pub async fn recon_merchant_account_update( }; let response = db - .update_merchant(merchant_account, updated_merchant_account, &key_store) + .update_merchant( + &(&state).into(), + merchant_account, + updated_merchant_account, + &key_store, + ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 5dc46d35652..ea9ce177439 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -474,12 +474,19 @@ pub async fn send_request( let should_bypass_proxy = url .as_str() .starts_with(&state.conf.connectors.dummyconnector.base_url) - || proxy_bypass_urls(&state.conf.locker, &state.conf.proxy.bypass_proxy_urls) - .contains(&url.to_string()); + || proxy_bypass_urls( + state.conf.key_manager.get_inner(), + &state.conf.locker, + &state.conf.proxy.bypass_proxy_urls, + ) + .contains(&url.to_string()); #[cfg(not(feature = "dummy_connector"))] - let should_bypass_proxy = - proxy_bypass_urls(&state.conf.locker, &state.conf.proxy.bypass_proxy_urls) - .contains(&url.to_string()); + let should_bypass_proxy = proxy_bypass_urls( + &state.conf.key_manager.get_inner(), + &state.conf.locker, + &state.conf.proxy.bypass_proxy_urls, + ) + .contains(&url.to_string()); let client = client::create_client( &state.conf.proxy, should_bypass_proxy, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index f3cb2f3f314..4dda8eab627 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -15,7 +15,7 @@ use crate::{ errors::{ApiClientError, CustomResult}, payments, }, - routes::SessionState, + routes::{app::settings::KeyManagerConfig, SessionState}, }; static NON_PROXIED_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); @@ -110,7 +110,12 @@ pub fn create_client( } } -pub fn proxy_bypass_urls(locker: &Locker, config_whitelist: &[String]) -> Vec<String> { +pub fn proxy_bypass_urls( + key_manager: &KeyManagerConfig, + locker: &Locker, + config_whitelist: &[String], +) -> Vec<String> { + let key_manager_host = key_manager.url.to_owned(); let locker_host = locker.host.to_owned(); let locker_host_rs = locker.host_rs.to_owned(); @@ -126,8 +131,11 @@ pub fn proxy_bypass_urls(locker: &Locker, config_whitelist: &[String]) -> Vec<St format!("{locker_host}/card/addCard"), format!("{locker_host}/card/getCard"), format!("{locker_host}/card/deleteCard"), + format!("{key_manager_host}/data/encrypt"), + format!("{key_manager_host}/data/decrypt"), + format!("{key_manager_host}/key/create"), + format!("{key_manager_host}/key/rotate"), ]; - [&proxy_list, config_whitelist].concat().to_vec() } diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index adc23935d9c..22c7f25ff82 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -319,9 +319,12 @@ where .attach_printable("API key has expired"); } + let key_manager_state = &(&state.session_state()).into(); + let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) @@ -331,7 +334,11 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; @@ -534,9 +541,11 @@ where _request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, self.0.as_ref(), &state.store().get_master_key().to_vec().into(), ) @@ -552,7 +561,7 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(self.0.as_ref(), &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, self.0.as_ref(), &key_store) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -590,10 +599,10 @@ where ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let publishable_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; - + let key_manager_state = &(&state.session_state()).into(); state .store() - .find_merchant_account_by_publishable_key(publishable_key) + .find_merchant_account_by_publishable_key(key_manager_state, publishable_key) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -818,10 +827,11 @@ where let permissions = authorization::get_permissions(state, &payload).await?; authorization::check_authorization(&self.0, &permissions)?; - + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) @@ -831,7 +841,11 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; @@ -868,10 +882,11 @@ where let permissions = authorization::get_permissions(state, &payload).await?; authorization::check_authorization(&self.0, &permissions)?; - + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) @@ -881,7 +896,11 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; @@ -963,10 +982,11 @@ where state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; - + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) @@ -976,7 +996,11 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 884e47c6fc4..054888d1dfe 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -8,13 +8,17 @@ pub use api_models::admin::{ MerchantId, PaymentMethodsEnabled, ToggleAllKVRequest, ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails, }; -use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; +use common_utils::{ + ext_traits::{AsyncExt, Encode, ValueExt}, + types::keymanager::Identifier, +}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{merchant_key_store::MerchantKeyStore, type_encryption::decrypt}; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ core::{errors, payment_methods::cards::create_encrypted_data}, + routes::SessionState, types::{domain, storage, transformers::ForeignTryFrom}, }; @@ -84,11 +88,14 @@ impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { } pub async fn business_profile_response( + state: &SessionState, item: storage::business_profile::BusinessProfile, key_store: &MerchantKeyStore, ) -> Result<BusinessProfileResponse, error_stack::Report<errors::ParsingError>> { let outgoing_webhook_custom_http_headers = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), item.outgoing_webhook_custom_http_headers.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.get_inner().peek(), ) .await @@ -147,6 +154,7 @@ pub async fn business_profile_response( } pub async fn create_business_profile( + state: &SessionState, merchant_account: domain::MerchantAccount, request: BusinessProfileCreate, key_store: &MerchantKeyStore, @@ -188,7 +196,7 @@ pub async fn create_business_profile( .transpose()?; let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers - .async_map(|headers| create_encrypted_data(key_store, headers)) + .async_map(|headers| create_encrypted_data(state, key_store, headers)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 71b90ab41c3..686f7f3ce49 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -2,7 +2,6 @@ use api_models::mandates; pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use common_utils::ext_traits::OptionExt; use error_stack::ResultExt; -use masking::PeekInterface; use serde::{Deserialize, Serialize}; use crate::{ @@ -73,8 +72,8 @@ impl MandateResponseExt for MandateResponse { } else { payment_methods::cards::get_card_details_without_locker_fallback( &payment_method, - key_store.key.get_inner().peek(), state, + &key_store, ) .await? }; diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index 0ed09a35013..e14ab8ea641 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -1,18 +1,19 @@ use async_trait::async_trait; use common_utils::{ - crypto, date_time, + crypto::{self, Encryptable}, + date_time, + encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; -use diesel_models::{address::AddressUpdateInternal, encryption::Encryption, enums}; +use diesel_models::{address::AddressUpdateInternal, enums}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; +use rustc_hash::FxHashMap; use time::{OffsetDateTime, PrimitiveDateTime}; -use super::{ - behaviour, - types::{self, AsyncLift}, -}; +use super::{behaviour, types}; #[derive(Clone, Debug, serde::Serialize)] pub struct Address { @@ -73,8 +74,10 @@ impl behaviour::Conversion for CustomerAddress { } async fn convert_back( + state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> { let customer_id = other @@ -84,7 +87,7 @@ impl behaviour::Conversion for CustomerAddress { field_name: "customer_id".to_string(), })?; - let address = Address::convert_back(other, key).await?; + let address = Address::convert_back(state, other, key, key_store_ref_id).await?; Ok(Self { address, @@ -117,8 +120,10 @@ impl behaviour::Conversion for PaymentAddress { } async fn convert_back( + state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> { let payment_id = other .payment_id @@ -129,7 +134,7 @@ impl behaviour::Conversion for PaymentAddress { let customer_id = other.customer_id.clone(); - let address = Address::convert_back(other, key).await?; + let address = Address::convert_back(state, other, key, key_store_ref_id).await?; Ok(Self { address, @@ -180,36 +185,45 @@ impl behaviour::Conversion for Address { } async fn convert_back( + state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> { - async { - let inner_decrypt = |inner| types::decrypt(inner, key.peek()); - let inner_decrypt_email = |inner| types::decrypt(inner, key.peek()); - Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - id: other.id, - address_id: other.address_id, - city: other.city, - country: other.country, - line1: other.line1.async_lift(inner_decrypt).await?, - line2: other.line2.async_lift(inner_decrypt).await?, - line3: other.line3.async_lift(inner_decrypt).await?, - state: other.state.async_lift(inner_decrypt).await?, - zip: other.zip.async_lift(inner_decrypt).await?, - first_name: other.first_name.async_lift(inner_decrypt).await?, - last_name: other.last_name.async_lift(inner_decrypt).await?, - phone_number: other.phone_number.async_lift(inner_decrypt).await?, - country_code: other.country_code, - created_at: other.created_at, - modified_at: other.modified_at, - updated_by: other.updated_by, - merchant_id: other.merchant_id, - email: other.email.async_lift(inner_decrypt_email).await?, - }) - } + let identifier = Identifier::Merchant(other.merchant_id.clone()); + let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::batch_decrypt( + state, + diesel_models::Address::to_encryptable(other.clone()), + identifier.clone(), + key.peek(), + ) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting".to_string(), + })?; + let encryptable_address = diesel_models::Address::from_encryptable(decrypted) + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting".to_string(), + })?; + Ok(Self { + id: other.id, + address_id: other.address_id, + city: other.city, + country: other.country, + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + state: encryptable_address.state, + zip: encryptable_address.zip, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, + phone_number: encryptable_address.phone_number, + country_code: other.country_code, + created_at: other.created_at, + modified_at: other.modified_at, + updated_by: other.updated_by, + merchant_id: other.merchant_id, + email: encryptable_address.email, }) } diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index c5b0b3701cb..b7ed05e3506 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -1,10 +1,16 @@ -use common_utils::{crypto, date_time, id_type, pii}; -use diesel_models::{customers::CustomerUpdateInternal, encryption::Encryption}; +use api_models::customers::CustomerRequestWithEncryption; +use common_utils::{ + crypto, date_time, + encryption::Encryption, + id_type, pii, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, +}; +use diesel_models::customers::CustomerUpdateInternal; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use time::PrimitiveDateTime; -use super::types::{self, AsyncLift}; +use super::types; use crate::errors::{CustomResult, ValidationError}; #[derive(Clone, Debug)] @@ -53,36 +59,49 @@ impl super::behaviour::Conversion for Customer { } async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { - async { - let inner_decrypt = |inner| types::decrypt(inner, key.peek()); - let inner_decrypt_email = |inner| types::decrypt(inner, key.peek()); - Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - id: Some(item.id), - customer_id: item.customer_id, - merchant_id: item.merchant_id, - name: item.name.async_lift(inner_decrypt).await?, - email: item.email.async_lift(inner_decrypt_email).await?, - phone: item.phone.async_lift(inner_decrypt).await?, - phone_country_code: item.phone_country_code, - description: item.description, - created_at: item.created_at, - metadata: item.metadata, - modified_at: item.modified_at, - connector_customer: item.connector_customer, - address_id: item.address_id, - default_payment_method_id: item.default_payment_method_id, - updated_by: item.updated_by, - }) - } + let decrypted = types::batch_decrypt( + state, + CustomerRequestWithEncryption::to_encryptable(CustomerRequestWithEncryption { + name: item.name.clone(), + phone: item.phone.clone(), + email: item.email.clone(), + }), + Identifier::Merchant(item.merchant_id.clone()), + key.peek(), + ) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), + })?; + let encryptable_customer = CustomerRequestWithEncryption::from_encryptable(decrypted) + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting customer data".to_string(), + })?; + + Ok(Self { + id: Some(item.id), + customer_id: item.customer_id, + merchant_id: item.merchant_id, + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: encryptable_customer.phone, + phone_country_code: item.phone_country_code, + description: item.description, + created_at: item.created_at, + metadata: item.metadata, + modified_at: item.modified_at, + connector_customer: item.connector_customer, + address_id: item.address_id, + default_payment_method_id: item.default_payment_method_id, + updated_by: item.updated_by, }) } diff --git a/crates/router/src/types/domain/event.rs b/crates/router/src/types/domain/event.rs index 74a6cfb47b5..c5eca1ab5ea 100644 --- a/crates/router/src/types/domain/event.rs +++ b/crates/router/src/types/domain/event.rs @@ -1,14 +1,18 @@ -use common_utils::crypto::OptionalEncryptableSecretString; +use common_utils::{ + crypto::OptionalEncryptableSecretString, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, +}; use diesel_models::{ enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt}, events::{EventMetadata, EventUpdateInternal}, + EventWithEncryption, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use crate::{ errors::{CustomResult, ValidationError}, - types::domain::types::{self, AsyncLift}, + types::domain::types, }; #[derive(Clone, Debug)] @@ -80,41 +84,49 @@ impl super::behaviour::Conversion for Event { } async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { - async { - Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - event_id: item.event_id, - event_type: item.event_type, - event_class: item.event_class, - is_webhook_notified: item.is_webhook_notified, - primary_object_id: item.primary_object_id, - primary_object_type: item.primary_object_type, - created_at: item.created_at, - merchant_id: item.merchant_id, - business_profile_id: item.business_profile_id, - primary_object_created_at: item.primary_object_created_at, - idempotent_event_id: item.idempotent_event_id, - initial_attempt_id: item.initial_attempt_id, - request: item - .request - .async_lift(|inner| types::decrypt(inner, key.peek())) - .await?, - response: item - .response - .async_lift(|inner| types::decrypt(inner, key.peek())) - .await?, - delivery_attempt: item.delivery_attempt, - metadata: item.metadata, - }) - } + let decrypted = types::batch_decrypt( + state, + EventWithEncryption::to_encryptable(EventWithEncryption { + request: item.request.clone(), + response: item.response.clone(), + }), + Identifier::Merchant(key_store_ref_id.clone()), + key.peek(), + ) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting event data".to_string(), + })?; + let encryptable_event = EventWithEncryption::from_encryptable(decrypted).change_context( + ValidationError::InvalidValue { + message: "Failed while decrypting event data".to_string(), + }, + )?; + Ok(Self { + event_id: item.event_id, + event_type: item.event_type, + event_class: item.event_class, + is_webhook_notified: item.is_webhook_notified, + primary_object_id: item.primary_object_id, + primary_object_type: item.primary_object_type, + created_at: item.created_at, + merchant_id: item.merchant_id, + business_profile_id: item.business_profile_id, + primary_object_created_at: item.primary_object_created_at, + idempotent_event_id: item.idempotent_event_id, + initial_attempt_id: item.initial_attempt_id, + request: encryptable_event.request, + response: encryptable_event.response, + delivery_attempt: item.delivery_attempt, + metadata: item.metadata, }) } diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 2cf091eda12..6f654848f60 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -1,13 +1,12 @@ use common_utils::{ crypto::{Encryptable, GcmAes256}, date_time, + encryption::Encryption, errors::{CustomResult, ValidationError}, pii, + types::keymanager::{Identifier, KeyManagerState}, }; -use diesel_models::{ - encryption::Encryption, enums, - merchant_connector_account::MerchantConnectorAccountUpdateInternal, -}; +use diesel_models::{enums, merchant_connector_account::MerchantConnectorAccountUpdateInternal}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -108,15 +107,20 @@ impl behaviour::Conversion for MerchantConnectorAccount { } async fn convert_back( + state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> { + let identifier = Identifier::Merchant(other.merchant_id.clone()); Ok(Self { id: Some(other.id), merchant_id: other.merchant_id, connector_name: other.connector_name, - connector_account_details: Encryptable::decrypt( + connector_account_details: Encryptable::decrypt_via_api( + state, other.connector_account_details, + identifier.clone(), key.peek(), GcmAes256, ) @@ -145,7 +149,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { status: other.status, connector_wallets_details: other .connector_wallets_details - .async_lift(|inner| types::decrypt(inner, key.peek())) + .async_lift(|inner| types::decrypt(state, inner, identifier.clone(), key.peek())) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector wallets details".to_string(), diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs index 151ae61f5fe..53239cd27cf 100644 --- a/crates/router/src/types/domain/types.rs +++ b/crates/router/src/types/domain/types.rs @@ -1,6 +1,7 @@ use common_utils::types::keymanager::KeyManagerState; pub use hyperswitch_domain_models::type_encryption::{ - decrypt, encrypt, encrypt_optional, AsyncLift, Lift, TypeEncryption, + batch_decrypt, batch_encrypt, decrypt, encrypt, encrypt_optional, AsyncLift, Lift, + TypeEncryption, }; impl From<&crate::SessionState> for KeyManagerState { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index c4c67796d46..ec44103a8f0 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -7,8 +7,11 @@ use common_enums::TokenPurpose; #[cfg(not(feature = "v2"))] use common_utils::id_type; #[cfg(feature = "keymanager_create")] -use common_utils::types::keymanager::{EncryptionCreateRequest, Identifier}; -use common_utils::{crypto::Encryptable, errors::CustomResult, new_type::MerchantName, pii}; +use common_utils::types::keymanager::EncryptionCreateRequest; +use common_utils::{ + crypto::Encryptable, errors::CustomResult, new_type::MerchantName, pii, + types::keymanager::Identifier, +}; use diesel_models::{ enums::{TotpStatus, UserStatus}, organization as diesel_org, @@ -368,6 +371,7 @@ impl NewUserMerchant { if state .store .get_merchant_key_store_by_merchant_id( + &(&state).into(), self.get_merchant_id().as_str(), &state.store.get_master_key().to_vec().into(), ) @@ -949,9 +953,14 @@ impl UserFromStorage { pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> { let master_key = state.store.get_master_key(); + let key_manager_state = &state.into(); let key_store_result = state .global_store - .get_user_key_store_by_user_id(self.get_user_id(), &master_key.to_vec().into()) + .get_user_key_store_by_user_id( + key_manager_state, + self.get_user_id(), + &master_key.to_vec().into(), + ) .await; if let Ok(key_store) = key_store_result { @@ -968,16 +977,21 @@ impl UserFromStorage { let key_store = UserKeyStore { user_id: self.get_user_id().to_string(), - key: domain_types::encrypt(key.to_vec().into(), master_key) - .await - .change_context(UserErrors::InternalServerError)?, + key: domain_types::encrypt( + key_manager_state, + key.to_vec().into(), + Identifier::User(self.get_user_id().to_string()), + master_key, + ) + .await + .change_context(UserErrors::InternalServerError)?, created_at: common_utils::date_time::now(), }; #[cfg(feature = "keymanager_create")] { common_utils::keymanager::create_key_in_key_manager( - &state.into(), + key_manager_state, EncryptionCreateRequest { identifier: Identifier::User(key_store.user_id.clone()), }, @@ -988,7 +1002,7 @@ impl UserFromStorage { state .global_store - .insert_user_key_store(key_store, &master_key.to_vec().into()) + .insert_user_key_store(key_manager_state, key_store, &master_key.to_vec().into()) .await .change_context(UserErrors::InternalServerError) } else { @@ -1014,10 +1028,11 @@ impl UserFromStorage { if self.0.totp_secret.is_none() { return Ok(None); } - + let key_manager_state = &state.into(); let user_key_store = state .global_store .get_user_key_store_by_user_id( + key_manager_state, self.get_user_id(), &state.store.get_master_key().to_vec().into(), ) @@ -1025,7 +1040,9 @@ impl UserFromStorage { .change_context(UserErrors::InternalServerError)?; Ok(domain_types::decrypt::<String, masking::WithType>( + key_manager_state, self.0.totp_secret.clone(), + Identifier::User(user_key_store.user_id.clone()), user_key_store.key.peek(), ) .await @@ -1141,6 +1158,7 @@ impl SignInWithMultipleRolesStrategy { let merchant_accounts = state .store .list_multiple_merchant_accounts( + &state.into(), self.user_roles .iter() .map(|role| role.merchant_id.clone()) diff --git a/crates/router/src/types/domain/user_key_store.rs b/crates/router/src/types/domain/user_key_store.rs index 4c1427d58dc..3a1a9a60e95 100644 --- a/crates/router/src/types/domain/user_key_store.rs +++ b/crates/router/src/types/domain/user_key_store.rs @@ -1,6 +1,7 @@ use common_utils::{ crypto::{Encryptable, GcmAes256}, date_time, + types::keymanager::{Identifier, KeyManagerState}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -32,14 +33,17 @@ impl super::behaviour::Conversion for UserKeyStore { } async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { + let identifier = Identifier::User(item.user_id.clone()); Ok(Self { - key: Encryptable::decrypt(item.key, key.peek(), GcmAes256) + key: Encryptable::decrypt_via_api(state, item.key, identifier, key.peek(), GcmAes256) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 64e2f534b7a..a36aee4593e 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -14,19 +14,25 @@ pub mod verify_connector; use std::fmt::Debug; -use api_models::{enums, payments, webhooks}; +use api_models::{ + enums, + payments::{self, AddressDetailsWithPhone}, + webhooks, +}; use base64::Engine; -use common_utils::id_type; pub use common_utils::{ crypto, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, validation::validate_email, }; +use common_utils::{ + id_type, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, +}; use error_stack::ResultExt; -use hyperswitch_domain_models::payments::PaymentIntent; +use hyperswitch_domain_models::{payments::PaymentIntent, type_encryption::batch_encrypt}; use image::Luma; -use masking::ExposeInterface; use nanoid::nanoid; use qrcode; use router_env::metrics::add_attributes; @@ -43,19 +49,10 @@ use crate::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, utils, webhooks as webhooks_core, }, - db::StorageInterface, logger, - routes::metrics, + routes::{metrics, SessionState}, services, - types::{ - self, - domain::{ - self, - types::{encrypt_optional, AsyncLift}, - }, - storage, - transformers::ForeignFrom, - }, + types::{self, domain, storage, transformers::ForeignFrom}, }; pub mod error_parser { @@ -194,14 +191,17 @@ impl QrImage { } pub async fn find_payment_intent_from_payment_id_type( - db: &dyn StorageInterface, + state: &SessionState, payment_id_type: payments::PaymentIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { + let key_manager_state: KeyManagerState = state.into(); + let db = &*state.store; match payment_id_type { payments::PaymentIdType::PaymentIntentId(payment_id) => db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, &payment_id, &merchant_account.merchant_id, key_store, @@ -219,6 +219,7 @@ pub async fn find_payment_intent_from_payment_id_type( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, &attempt.payment_id, &merchant_account.merchant_id, key_store, @@ -237,6 +238,7 @@ pub async fn find_payment_intent_from_payment_id_type( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, &attempt.payment_id, &merchant_account.merchant_id, key_store, @@ -252,12 +254,13 @@ pub async fn find_payment_intent_from_payment_id_type( } pub async fn find_payment_intent_from_refund_id_type( - db: &dyn StorageInterface, + state: &SessionState, refund_id_type: webhooks::RefundIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector_name: &str, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { + let db = &*state.store; let refund = match refund_id_type { webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( @@ -286,6 +289,7 @@ pub async fn find_payment_intent_from_refund_id_type( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( + &state.into(), &attempt.payment_id, &merchant_account.merchant_id, key_store, @@ -296,11 +300,12 @@ pub async fn find_payment_intent_from_refund_id_type( } pub async fn find_payment_intent_from_mandate_id_type( - db: &dyn StorageInterface, + state: &SessionState, mandate_id_type: webhooks::MandateIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { + let db = &*state.store; let mandate = match mandate_id_type { webhooks::MandateIdType::MandateId(mandate_id) => db .find_mandate_by_merchant_id_mandate_id( @@ -320,6 +325,7 @@ pub async fn find_payment_intent_from_mandate_id_type( .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, }; db.find_payment_intent_by_payment_id_merchant_id( + &state.into(), &mandate .original_payment_id .ok_or(errors::ApiErrorResponse::InternalServerError) @@ -333,11 +339,12 @@ pub async fn find_payment_intent_from_mandate_id_type( } pub async fn find_mca_from_authentication_id_type( - db: &dyn StorageInterface, + state: &SessionState, authentication_id_type: webhooks::AuthenticationIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = &*state.store; let authentication = match authentication_id_type { webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db .find_authentication_by_merchant_id_authentication_id( @@ -356,6 +363,7 @@ pub async fn find_mca_from_authentication_id_type( } }; db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &state.into(), &merchant_account.merchant_id, &authentication.merchant_connector_id, key_store, @@ -367,12 +375,13 @@ pub async fn find_mca_from_authentication_id_type( } pub async fn get_mca_from_payment_intent( - db: &dyn StorageInterface, + state: &SessionState, merchant_account: &domain::MerchantAccount, payment_intent: PaymentIntent, key_store: &domain::MerchantKeyStore, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = &*state.store; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), @@ -381,10 +390,11 @@ pub async fn get_mca_from_payment_intent( ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - + let key_manager_state = &state.into(); match payment_attempt.merchant_connector_id { Some(merchant_connector_id) => db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_account.merchant_id, &merchant_connector_id, key_store, @@ -410,6 +420,7 @@ pub async fn get_mca_from_payment_intent( }; db.find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, &profile_id, connector_name, key_store, @@ -426,12 +437,13 @@ pub async fn get_mca_from_payment_intent( #[cfg(feature = "payouts")] pub async fn get_mca_from_payout_attempt( - db: &dyn StorageInterface, + state: &SessionState, merchant_account: &domain::MerchantAccount, payout_id_type: webhooks::PayoutIdType, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = &*state.store; let payout = match payout_id_type { webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db .find_payout_attempt_by_merchant_id_payout_attempt_id( @@ -450,10 +462,11 @@ pub async fn get_mca_from_payout_attempt( .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, }; - + let key_manager_state = &state.into(); match payout.merchant_connector_id { Some(merchant_connector_id) => db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_account.merchant_id, &merchant_connector_id, key_store, @@ -464,6 +477,7 @@ pub async fn get_mca_from_payout_attempt( }), None => db .find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, &payout.profile_id, connector_name, key_store, @@ -479,15 +493,17 @@ pub async fn get_mca_from_payout_attempt( } pub async fn get_mca_from_object_reference_id( - db: &dyn StorageInterface, + state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_account: &domain::MerchantAccount, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = &*state.store; match merchant_account.default_profile.as_ref() { Some(profile_id) => db .find_merchant_connector_account_by_profile_id_connector_name( + &state.into(), profile_id, connector_name, key_store, @@ -499,10 +515,10 @@ pub async fn get_mca_from_object_reference_id( _ => match object_reference_id { webhooks::ObjectReferenceId::PaymentId(payment_id_type) => { get_mca_from_payment_intent( - db, + state, merchant_account, find_payment_intent_from_payment_id_type( - db, + state, payment_id_type, merchant_account, key_store, @@ -515,10 +531,10 @@ pub async fn get_mca_from_object_reference_id( } webhooks::ObjectReferenceId::RefundId(refund_id_type) => { get_mca_from_payment_intent( - db, + state, merchant_account, find_payment_intent_from_refund_id_type( - db, + state, refund_id_type, merchant_account, key_store, @@ -532,10 +548,10 @@ pub async fn get_mca_from_object_reference_id( } webhooks::ObjectReferenceId::MandateId(mandate_id_type) => { get_mca_from_payment_intent( - db, + state, merchant_account, find_payment_intent_from_mandate_id_type( - db, + state, mandate_id_type, merchant_account, key_store, @@ -548,7 +564,7 @@ pub async fn get_mca_from_object_reference_id( } webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => { find_mca_from_authentication_id_type( - db, + state, authentication_id_type, merchant_account, key_store, @@ -558,7 +574,7 @@ pub async fn get_mca_from_object_reference_id( #[cfg(feature = "payouts")] webhooks::ObjectReferenceId::PayoutId(payout_id_type) => { get_mca_from_payout_attempt( - db, + state, merchant_account, payout_id_type, connector_name, @@ -649,13 +665,16 @@ pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) { pub trait CustomerAddress { async fn get_address_update( &self, + state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, + merchant_id: String, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, + state: &SessionState, address_details: payments::AddressDetails, merchant_id: &str, customer_id: &id_type::CustomerId, @@ -668,126 +687,89 @@ pub trait CustomerAddress { impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_address_update( &self, + state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, + merchant_id: String, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { - async { - Ok(storage::AddressUpdate::Update { - city: address_details.city, - country: address_details.country, - line1: address_details - .line1 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - line2: address_details - .line2 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - line3: address_details - .line3 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - zip: address_details - .zip - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - state: address_details - .state - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - first_name: address_details - .first_name - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - last_name: address_details - .last_name - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - phone_number: self - .phone - .clone() - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - country_code: self.phone_country_code.clone(), - updated_by: storage_scheme.to_string(), - email: self - .email - .as_ref() - .cloned() - .async_lift(|inner| encrypt_optional(inner.map(|inner| inner.expose()), key)) - .await?, - }) - } - .await + let encrypted_data = batch_encrypt( + &state.into(), + AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone { + address: Some(address_details.clone()), + phone_number: self.phone.clone(), + email: self.email.clone(), + }), + Identifier::Merchant(merchant_id), + key, + ) + .await?; + let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + Ok(storage::AddressUpdate::Update { + city: address_details.city, + country: address_details.country, + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + zip: encryptable_address.zip, + state: encryptable_address.state, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, + phone_number: encryptable_address.phone_number, + country_code: self.phone_country_code.clone(), + updated_by: storage_scheme.to_string(), + email: encryptable_address.email, + }) } async fn get_domain_address( &self, + state: &SessionState, address_details: payments::AddressDetails, merchant_id: &str, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { - async { - let address = domain::Address { - id: None, - city: address_details.city, - country: address_details.country, - line1: address_details - .line1 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - line2: address_details - .line2 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - line3: address_details - .line3 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - zip: address_details - .zip - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - state: address_details - .state - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - first_name: address_details - .first_name - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - last_name: address_details - .last_name - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - phone_number: self - .phone - .clone() - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - country_code: self.phone_country_code.clone(), - merchant_id: merchant_id.to_string(), - address_id: generate_id(consts::ID_LENGTH, "add"), - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), - updated_by: storage_scheme.to_string(), - email: self - .email - .as_ref() - .cloned() - .async_lift(|inner| encrypt_optional(inner.map(|inner| inner.expose()), key)) - .await?, - }; + let encrypted_data = batch_encrypt( + &state.into(), + AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone { + address: Some(address_details.clone()), + phone_number: self.phone.clone(), + email: self.email.clone(), + }), + Identifier::Merchant(merchant_id.to_string()), + key, + ) + .await?; + let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + let address = domain::Address { + id: None, + city: address_details.city, + country: address_details.country, + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + zip: encryptable_address.zip, + state: encryptable_address.state, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, + phone_number: encryptable_address.phone_number, + country_code: self.phone_country_code.clone(), + merchant_id: merchant_id.to_string(), + address_id: generate_id(consts::ID_LENGTH, "add"), + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + updated_by: storage_scheme.to_string(), + email: encryptable_address.email, + }; - Ok(domain::CustomerAddress { - address, - customer_id: customer_id.to_owned(), - }) - } - .await + Ok(domain::CustomerAddress { + address, + customer_id: customer_id.to_owned(), + }) } } @@ -911,7 +893,7 @@ pub async fn trigger_payments_webhook<F, Op>( key_store: &domain::MerchantKeyStore, payment_data: crate::core::payments::PaymentData<F>, customer: Option<domain::Customer>, - state: &crate::routes::SessionState, + state: &SessionState, operation: Op, ) -> RouterResult<()> where diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rs index 15ad2eb8954..0bc8e58fcc4 100644 --- a/crates/router/src/utils/connector_onboarding.rs +++ b/crates/router/src/utils/connector_onboarding.rs @@ -45,9 +45,11 @@ pub async fn check_if_connector_exists( connector_id: &str, merchant_id: &str, ) -> RouterResult<()> { + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -57,6 +59,7 @@ pub async fn check_if_connector_exists( let _connector = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, merchant_id, connector_id, &key_store, diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 3cd35886ffe..9734122a260 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -2,8 +2,8 @@ use std::{collections::HashMap, sync::Arc}; use api_models::user as user_api; use common_enums::UserAuthType; -use common_utils::errors::CustomResult; -use diesel_models::{encryption::Encryption, enums::UserStatus, user_role::UserRole}; +use common_utils::{encryption::Encryption, errors::CustomResult, types::keymanager::Identifier}; +use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; @@ -33,9 +33,11 @@ impl UserFromToken { &self, state: SessionState, ) -> UserResult<MerchantAccount> { + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &self.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -49,7 +51,7 @@ impl UserFromToken { })?; let merchant_account = state .store - .find_merchant_account_by_merchant_id(&self.merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &self.merchant_id, &key_store) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -218,8 +220,10 @@ impl ForeignFrom<&user_api::AuthConfig> for UserAuthType { } pub async fn construct_public_and_private_db_configs( + state: &SessionState, auth_config: &user_api::AuthConfig, encryption_key: &[u8], + id: String, ) -> UserResult<(Option<Encryption>, Option<serde_json::Value>)> { match auth_config { user_api::AuthConfig::OpenIdConnect { @@ -231,7 +235,9 @@ pub async fn construct_public_and_private_db_configs( .attach_printable("Failed to convert auth config to json")?; let encrypted_config = domain::types::encrypt::<serde_json::Value, masking::WithType>( + &state.into(), private_config_value.into(), + Identifier::UserAuth(id), encryption_key, ) .await @@ -263,6 +269,7 @@ where pub async fn decrypt_oidc_private_config( state: &SessionState, encrypted_config: Option<Encryption>, + id: String, ) -> UserResult<user_api::OpenIdConnectPrivateConfig> { let user_auth_key = hex::decode( state @@ -277,7 +284,9 @@ pub async fn decrypt_oidc_private_config( .attach_printable("Failed to decode DEK")?; let private_config = domain::types::decrypt::<serde_json::Value, masking::WithType>( + &state.into(), encrypted_config, + Identifier::UserAuth(id), &user_auth_key, ) .await diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index b817d3e1cd7..0909f4ffbeb 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -23,7 +23,7 @@ pub async fn generate_sample_data( ) -> SampleDataResult<Vec<(PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>)>> { let merchant_id = merchant_id.to_string(); let sample_data_size: usize = req.record.unwrap_or(100); - + let key_manager_state = &state.into(); if !(10..=100).contains(&sample_data_size) { return Err(SampleDataError::InvalidRange.into()); } @@ -31,6 +31,7 @@ pub async fn generate_sample_data( let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id.as_str(), &state.store.get_master_key().to_vec().into(), ) @@ -39,7 +40,7 @@ pub async fn generate_sample_data( let merchant_from_db = state .store - .find_merchant_account_by_merchant_id(merchant_id.as_str(), &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id.as_str(), &key_store) .await .change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?; diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index dc39de8f933..e49a5f86c3c 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -28,17 +28,22 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { .tracking_data .clone() .parse_value("ApiKeyExpiryTrackingData")?; - + let key_manager_satte = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_satte, tracking_data.merchant_id.as_str(), &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db - .find_merchant_account_by_merchant_id(tracking_data.merchant_id.as_str(), &key_store) + .find_merchant_account_by_merchant_id( + key_manager_satte, + tracking_data.merchant_id.as_str(), + &key_store, + ) .await?; let email_id = merchant_account diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rs index eb60510ad75..7ff0faefa68 100644 --- a/crates/router/src/workflows/attach_payout_account_workflow.rs +++ b/crates/router/src/workflows/attach_payout_account_workflow.rs @@ -31,16 +31,17 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow { .merchant_id .clone() .get_required_value("merchant_id")?; - + let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id.as_ref(), &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await?; let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data); diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index a8d5c28b64f..d181aedd18f 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -43,8 +43,10 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { .parse_value("OutgoingWebhookTrackingData")?; let db = &*state.store; + let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, &tracking_data.merchant_id, &db.get_master_key().to_vec().into(), ) @@ -63,6 +65,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { let initial_event = match &tracking_data.initial_attempt_id { Some(initial_attempt_id) => { db.find_event_by_merchant_id_event_id( + key_manager_state, &business_profile.merchant_id, initial_attempt_id, &key_store, @@ -77,6 +80,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { tracking_data.primary_object_id, tracking_data.event_type ); db.find_event_by_merchant_id_event_id( + key_manager_state, &business_profile.merchant_id, &old_event_id, &key_store, @@ -106,7 +110,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { }; let event = db - .insert_event(new_event, &key_store) + .insert_event(key_manager_state, new_event, &key_store) .await .map_err(|error| { logger::error!(?error, "Failed to insert event in events table"); @@ -137,7 +141,11 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { // resource None => { let merchant_account = db - .find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &tracking_data.merchant_id, + &key_store, + ) .await?; // TODO: Add request state for the PT flows as well @@ -162,6 +170,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { }; let request_content = webhooks_core::get_outgoing_webhook_request( + state, &merchant_account, outgoing_webhook, &business_profile, diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs index b8e57360d90..fa0631cc5c2 100644 --- a/crates/router/src/workflows/payment_method_status_update.rs +++ b/crates/router/src/workflows/payment_method_status_update.rs @@ -30,17 +30,18 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow let prev_pm_status = tracking_data.prev_status; let curr_pm_status = tracking_data.curr_status; let merchant_id = tracking_data.merchant_id; - + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id.as_str(), &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await?; let payment_method = db diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index ef0fe07e9b7..2bc7b183ec1 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -38,9 +38,10 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { .tracking_data .clone() .parse_value("PaymentsRetrieveRequest")?; - + let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, tracking_data .merchant_id .as_ref() @@ -51,6 +52,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { let merchant_account = db .find_merchant_account_by_merchant_id( + key_manager_state, tracking_data .merchant_id .as_ref() @@ -148,6 +150,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { payment_data.payment_intent = db .update_payment_intent( + &state.into(), payment_data.payment_intent, payment_intent_update, &key_store, diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index ed11f3b8b1c..997ae51cf31 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -288,10 +288,11 @@ async fn payments_create_core() { let state = Arc::new(app_state) .get_session_state("public", || {}) .unwrap(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, "juspay_merchant", &state.store.get_master_key().to_vec().into(), ) @@ -300,7 +301,7 @@ async fn payments_create_core() { let merchant_account = state .store - .find_merchant_account_by_merchant_id("juspay_merchant", &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store) .await .unwrap(); @@ -476,10 +477,11 @@ async fn payments_create_core_adyen_no_redirect() { let customer_id = format!("cust_{}", Uuid::new_v4()); let merchant_id = "arunraj".to_string(); let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, "juspay_merchant", &state.store.get_master_key().to_vec().into(), ) @@ -488,7 +490,7 @@ async fn payments_create_core_adyen_no_redirect() { let merchant_account = state .store - .find_merchant_account_by_merchant_id("juspay_merchant", &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store) .await .unwrap(); diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 4c178e4122b..fcf106a9efc 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -48,10 +48,11 @@ async fn payments_create_core() { let state = Arc::new(app_state) .get_session_state("public", || {}) .unwrap(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, "juspay_merchant", &state.store.get_master_key().to_vec().into(), ) @@ -60,7 +61,7 @@ async fn payments_create_core() { let merchant_account = state .store - .find_merchant_account_by_merchant_id("juspay_merchant", &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store) .await .unwrap(); @@ -243,10 +244,11 @@ async fn payments_create_core_adyen_no_redirect() { let customer_id = format!("cust_{}", Uuid::new_v4()); let merchant_id = "arunraj".to_string(); let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, "juspay_merchant", &state.store.get_master_key().to_vec().into(), ) @@ -255,7 +257,7 @@ async fn payments_create_core_adyen_no_redirect() { let merchant_account = state .store - .find_merchant_account_by_merchant_id("juspay_merchant", &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store) .await .unwrap(); diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index bf3ce0baaab..3e183b94c26 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -1,4 +1,4 @@ -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use hyperswitch_domain_models::{ @@ -19,6 +19,7 @@ impl PaymentIntentInterface for MockDb { #[cfg(feature = "olap")] async fn filter_payment_intent_by_constraints( &self, + _state: &KeyManagerState, _merchant_id: &str, _filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, @@ -30,6 +31,7 @@ impl PaymentIntentInterface for MockDb { #[cfg(feature = "olap")] async fn filter_payment_intents_by_time_range_constraints( &self, + _state: &KeyManagerState, _merchant_id: &str, _time_range: &api_models::payments::TimeRange, _key_store: &MerchantKeyStore, @@ -51,6 +53,7 @@ impl PaymentIntentInterface for MockDb { #[cfg(feature = "olap")] async fn get_filtered_payment_intents_attempt( &self, + _state: &KeyManagerState, _merchant_id: &str, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, @@ -63,6 +66,7 @@ impl PaymentIntentInterface for MockDb { #[allow(clippy::panic)] async fn insert_payment_intent( &self, + _state: &KeyManagerState, new: PaymentIntent, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, @@ -76,6 +80,7 @@ impl PaymentIntentInterface for MockDb { #[allow(clippy::unwrap_used)] async fn update_payment_intent( &self, + state: &KeyManagerState, this: PaymentIntent, update: PaymentIntentUpdate, key_store: &MerchantKeyStore, @@ -95,8 +100,10 @@ impl PaymentIntentInterface for MockDb { .change_context(StorageError::EncryptionError)?; *payment_intent = PaymentIntent::convert_back( + state, diesel_payment_intent_update.apply_changeset(diesel_payment_intent), key_store.key.get_inner(), + key_store.merchant_id.clone(), ) .await .change_context(StorageError::DecryptionError)?; @@ -108,6 +115,7 @@ impl PaymentIntentInterface for MockDb { #[allow(clippy::unwrap_used)] async fn find_payment_intent_by_payment_id_merchant_id( &self, + _state: &KeyManagerState, payment_id: &str, merchant_id: &str, _key_store: &MerchantKeyStore, diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 62854cb261a..ced94b5717b 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -4,7 +4,10 @@ use api_models::payments::AmountFilter; use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; #[cfg(feature = "olap")] use common_utils::errors::ReportSwitchExt; -use common_utils::ext_traits::{AsyncExt, Encode}; +use common_utils::{ + ext_traits::{AsyncExt, Encode}, + types::keymanager::KeyManagerState, +}; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; use diesel_models::{ @@ -53,6 +56,7 @@ use crate::{ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { async fn insert_payment_intent( &self, + state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -69,7 +73,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store - .insert_payment_intent(payment_intent, merchant_key_store, storage_scheme) + .insert_payment_intent( + state, + payment_intent, + merchant_key_store, + storage_scheme, + ) .await } @@ -121,6 +130,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[instrument(skip_all)] async fn update_payment_intent( &self, + state: &KeyManagerState, this: PaymentIntent, payment_intent_update: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, @@ -143,6 +153,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_intent( + state, this, payment_intent_update, merchant_key_store, @@ -189,10 +200,14 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .try_into_hset() .change_context(StorageError::KVError)?; - let payment_intent = - PaymentIntent::convert_back(diesel_intent, merchant_key_store.key.get_inner()) - .await - .change_context(StorageError::DecryptionError)?; + let payment_intent = PaymentIntent::convert_back( + state, + diesel_intent, + merchant_key_store.key.get_inner(), + merchant_id, + ) + .await + .change_context(StorageError::DecryptionError)?; Ok(payment_intent) } @@ -202,6 +217,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, + state: &KeyManagerState, payment_id: &str, merchant_id: &str, merchant_key_store: &MerchantKeyStore, @@ -243,9 +259,14 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { } }?; - PaymentIntent::convert_back(diesel_payment_intent, merchant_key_store.key.get_inner()) - .await - .change_context(StorageError::DecryptionError) + PaymentIntent::convert_back( + state, + diesel_payment_intent, + merchant_key_store.key.get_inner(), + merchant_id.to_string(), + ) + .await + .change_context(StorageError::DecryptionError) } async fn get_active_payment_attempt( @@ -278,6 +299,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[cfg(feature = "olap")] async fn filter_payment_intent_by_constraints( &self, + state: &KeyManagerState, merchant_id: &str, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -285,6 +307,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intent_by_constraints( + state, merchant_id, filters, merchant_key_store, @@ -296,6 +319,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[cfg(feature = "olap")] async fn filter_payment_intents_by_time_range_constraints( &self, + state: &KeyManagerState, merchant_id: &str, time_range: &api_models::payments::TimeRange, merchant_key_store: &MerchantKeyStore, @@ -303,6 +327,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intents_by_time_range_constraints( + state, merchant_id, time_range, merchant_key_store, @@ -314,6 +339,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[cfg(feature = "olap")] async fn get_filtered_payment_intents_attempt( &self, + state: &KeyManagerState, merchant_id: &str, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -321,6 +347,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { self.router_store .get_filtered_payment_intents_attempt( + state, merchant_id, filters, merchant_key_store, @@ -351,6 +378,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn insert_payment_intent( &self, + state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -367,14 +395,20 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { er.change_context(new_err) })?; - PaymentIntent::convert_back(diesel_payment_intent, merchant_key_store.key.get_inner()) - .await - .change_context(StorageError::DecryptionError) + PaymentIntent::convert_back( + state, + diesel_payment_intent, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) + .await + .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_payment_intent( &self, + state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, @@ -394,14 +428,20 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { er.change_context(new_err) })?; - PaymentIntent::convert_back(diesel_payment_intent, merchant_key_store.key.get_inner()) - .await - .change_context(StorageError::DecryptionError) + PaymentIntent::convert_back( + state, + diesel_payment_intent, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) + .await + .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, + state: &KeyManagerState, payment_id: &str, merchant_id: &str, merchant_key_store: &MerchantKeyStore, @@ -417,8 +457,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { }) .async_and_then(|diesel_payment_intent| async { PaymentIntent::convert_back( + state, diesel_payment_intent, merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), ) .await .change_context(StorageError::DecryptionError) @@ -458,6 +500,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn filter_payment_intent_by_constraints( &self, + state: &KeyManagerState, merchant_id: &str, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -498,6 +541,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( + state, starting_after_id, merchant_id, merchant_key_store, @@ -516,6 +560,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( + state, ending_before_id, merchant_id, merchant_key_store, @@ -560,8 +605,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .map(|payment_intents| { try_join_all(payment_intents.into_iter().map(|diesel_payment_intent| { PaymentIntent::convert_back( + state, diesel_payment_intent, merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) @@ -579,6 +626,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn filter_payment_intents_by_time_range_constraints( &self, + state: &KeyManagerState, merchant_id: &str, time_range: &api_models::payments::TimeRange, merchant_key_store: &MerchantKeyStore, @@ -587,6 +635,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Remove this redundant function let payment_filters = (*time_range).into(); self.filter_payment_intent_by_constraints( + state, merchant_id, &payment_filters, merchant_key_store, @@ -599,6 +648,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, + state: &KeyManagerState, merchant_id: &str, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -640,6 +690,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( + state, starting_after_id, merchant_id, merchant_key_store, @@ -658,6 +709,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( + state, ending_before_id, merchant_id, merchant_key_store, @@ -745,13 +797,17 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .await .map(|results| { try_join_all(results.into_iter().map(|(pi, pa)| { - PaymentIntent::convert_back(pi, merchant_key_store.key.get_inner()).map( - |payment_intent| { - payment_intent.map(|payment_intent| { - (payment_intent, PaymentAttempt::from_storage_model(pa)) - }) - }, + PaymentIntent::convert_back( + state, + pi, + merchant_key_store.key.get_inner(), + merchant_id.to_string(), ) + .map(|payment_intent| { + payment_intent.map(|payment_intent| { + (payment_intent, PaymentAttempt::from_storage_model(pa)) + }) + }) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })
2024-06-28T14:15:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context PCI compliance requires application to follow some standards where encryption and decryption should not happen within the application as snapshot might have DEK and data together. So separate service should be used for encryption and decryption. In application wherever we are calling encrypt and decrypt it will be replaced by API call to encryption service. ## How did you test it? Changes can be verified only through logs. Look for "Fall back to Application Encryption" or "Fall back to Application Decryption" in the logs post deployment after running below tests. If logs are present encryption/decryption failed with encryption service and fall back to the application encryption which has to be investigated. **Test with merchant created before the changes deployed** 1. Create Payment 2. Retrieve Payment 3. Create Refund 4. Retrieve Payment **Test with merchant created after the changes deployed** 1. Create Merchant 2. Create API Key 3. Create MCA 4. Create Payment 6. Retrieve Payment 7. Create Refund 8. Retrieve Payment **Requires sanity on all the flows** ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
7f582e4737c1c7dfe906e7d01de239e131511f84
juspay/hyperswitch
juspay__hyperswitch-5254
Bug: [CI]: set `fail_fast` to false in the CI Because of this field that was set in the CI-pr.yaml, we were failing the CI being run on github actions if the CI being run on hyperswitch runners fails.
2024-07-09T09:32:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] CI/CD ## Description <!-- Describe your changes in detail --> Set `fail_fast` to false in the Ci ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
071d5345b5801e124da18d679202b0a60033b2f5
juspay/hyperswitch
juspay__hyperswitch-5249
Bug: [BUG] Payout in stages ### Bug Description - Default status (based on different conditions) does not update in payouts table - Payout status updation during confirmation happens prior to validating the request - Helper functions for deciding whether or not to execute different payout flows does not have the updated status list Payout in stages is broken. ### Expected Behavior Let me create a payout, be able to update it, confirm it and finally fulfill it. ### Actual Behavior It's letting me create a payout, while updating, it does not let me even access the API as the status conditions do not match (since default status was not updated in payouts table). It also does not respect the `confirm` field which is responsible for deciding and triggering core payout flows. ### Steps To Reproduce - Create a payout with `confirm: false` - Try to update this payout (you shall see an error) ### Context For The Bug Not needed. ### Environment Not needed. ### 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/payouts.rs b/crates/router/src/core/payouts.rs index f6f78094943..7d5dd908fdb 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -368,8 +368,6 @@ pub async fn payouts_confirm_core( let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; - helpers::update_payouts_and_payout_attempt(&mut payout_data, &merchant_account, &req, &state) - .await?; helpers::validate_payout_status_against_not_allowed_statuses( &status, &[ @@ -384,10 +382,11 @@ pub async fn payouts_confirm_core( "confirm", )?; - // Update payout link's status + helpers::update_payouts_and_payout_attempt(&mut payout_data, &merchant_account, &req, &state) + .await?; + let db = &*state.store; - // payout_data.payout_link payout_data.payout_link = payout_data .payout_link .clone() @@ -467,15 +466,17 @@ pub async fn payouts_update_core( ) .await?; - payouts_core( - &state, - &merchant_account, - &key_store, - &mut payout_data, - req.routing.clone(), - req.connector.clone(), - ) - .await?; + if let Some(true) = payout_data.payouts.confirm { + payouts_core( + &state, + &merchant_account, + &key_store, + &mut payout_data, + req.routing.clone(), + req.connector.clone(), + ) + .await?; + } response_handler(&merchant_account, &payout_data).await } @@ -2052,6 +2053,18 @@ pub async fn payout_create_db_entries( format!("payout_{payout_id}_secret").as_str(), ); let amount = MinorUnit::from(req.amount.unwrap_or(api::Amount::Zero)); + let status = if req.payout_method_data.is_some() + || req.payout_token.is_some() + || stored_payout_method_data.is_some() + { + match req.confirm { + Some(true) => storage_enums::PayoutStatus::RequiresCreation, + _ => storage_enums::PayoutStatus::RequiresConfirmation, + } + } else { + storage_enums::PayoutStatus::RequiresPayoutMethodData + }; + let payouts_req = storage::PayoutsNew { payout_id: payout_id.to_string(), merchant_id: merchant_id.to_string(), @@ -2076,6 +2089,7 @@ pub async fn payout_create_db_entries( .map(|link_data| link_data.link_id.clone()), client_secret: Some(client_secret), priority: req.priority, + status, ..Default::default() }; let payouts = db @@ -2086,17 +2100,6 @@ pub async fn payout_create_db_entries( }) .attach_printable("Error inserting payouts in db")?; // Make payout_attempt entry - let status = if req.payout_method_data.is_some() - || req.payout_token.is_some() - || stored_payout_method_data.is_some() - { - match req.confirm { - Some(true) => storage_enums::PayoutStatus::RequiresCreation, - _ => storage_enums::PayoutStatus::RequiresConfirmation, - } - } else { - storage_enums::PayoutStatus::RequiresPayoutMethodData - }; let payout_attempt_id = utils::get_payment_attempt_id(payout_id, 1); let payout_attempt_req = storage::PayoutAttemptNew { diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index ba00370e881..423e92fafc3 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -880,9 +880,12 @@ pub async fn get_gsm_record( } pub fn is_payout_initiated(status: api_enums::PayoutStatus) -> bool { - matches!( + !matches!( status, - api_enums::PayoutStatus::Pending | api_enums::PayoutStatus::RequiresFulfillment + api_enums::PayoutStatus::RequiresCreation + | api_enums::PayoutStatus::RequiresConfirmation + | api_enums::PayoutStatus::RequiresPayoutMethodData + | api_enums::PayoutStatus::RequiresVendorAccountCreation ) } @@ -903,10 +906,13 @@ pub(crate) fn validate_payout_status_against_not_allowed_statuses( pub fn is_payout_terminal_state(status: api_enums::PayoutStatus) -> bool { !matches!( status, - api_enums::PayoutStatus::Pending - | api_enums::PayoutStatus::RequiresCreation - | api_enums::PayoutStatus::RequiresFulfillment + api_enums::PayoutStatus::RequiresCreation + | api_enums::PayoutStatus::RequiresConfirmation | api_enums::PayoutStatus::RequiresPayoutMethodData + | api_enums::PayoutStatus::RequiresVendorAccountCreation + // Initiated by the underlying connector + | api_enums::PayoutStatus::Pending + | api_enums::PayoutStatus::RequiresFulfillment ) } @@ -923,7 +929,9 @@ pub fn is_eligible_for_local_payout_cancellation(status: api_enums::PayoutStatus matches!( status, api_enums::PayoutStatus::RequiresCreation - | api_enums::PayoutStatus::RequiresPayoutMethodData, + | api_enums::PayoutStatus::RequiresConfirmation + | api_enums::PayoutStatus::RequiresPayoutMethodData + | api_enums::PayoutStatus::RequiresVendorAccountCreation ) }
2024-07-09T05:42:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR fixes below bugs - default status (based on different conditions) does not update in `payouts` table - payout status updation during confirmation happens prior to validating the request - helper functions for deciding whether or not to execute different payout flows does not have the updated status list ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Tested locally using payout's test suite. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a payout using confirm: false, auto_fulfill: false ``` curl --location 'https://heard-directly-trademarks-diana.trycloudflare.com/payouts/create' \ --header 'x-feature: integ-custom' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_N4b6S09H8f5CHy1vvGEEyvyJcUqcs64R84eVkCtdBr3iTYFOGhCHieJlkoJUSs7w' \ --data-raw '{ "amount": 1, "currency": "EUR", "customer_id": "cus_ZcGmeCSo9O0YMHx8S9KT", "email": "payout_customer@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payout request", "payout_type": "wallet", "payout_method_data": { "wallet": { "paypal": { "email": "example@example.com" } } }, "connector": [ "adyen" ], "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "entity_type": "NaturalPerson", "recurring": true, "metadata": { "ref": "123" }, "confirm": false, "auto_fulfill": false }' ``` 2. Confirm payout ``` curl --location 'https://heard-directly-trademarks-diana.trycloudflare.com/payouts/46e549bf-8f7c-491f-96c7-f79087074b3d/confirm' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_N4b6S09H8f5CHy1vvGEEyvyJcUqcs64R84eVkCtdBr3iTYFOGhCHieJlkoJUSs7w' \ --data '{ }' ``` 3. Fulfill payout ``` curl --location 'https://heard-directly-trademarks-diana.trycloudflare.com/payouts/46e549bf-8f7c-491f-96c7-f79087074b3d/fulfill' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_N4b6S09H8f5CHy1vvGEEyvyJcUqcs64R84eVkCtdBr3iTYFOGhCHieJlkoJUSs7w' \ --data '{ }' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ffc79674e44d9b50bddbf4f4ac4aad0895c655db
juspay/hyperswitch
juspay__hyperswitch-5263
Bug: [Bug] - modified_at not updated for every state change - [ ] Refunds - https://github.com/juspay/hyperswitch/issues/5266
diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs index aa1d397797d..d695d2a0e70 100644 --- a/crates/diesel_models/src/address.rs +++ b/crates/diesel_models/src/address.rs @@ -1,5 +1,5 @@ use common_utils::id_type; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -29,8 +29,8 @@ pub struct AddressNew { pub email: Option<Encryption>, } -#[derive(Clone, Debug, Queryable, Identifiable, Serialize, Deserialize)] -#[diesel(table_name = address, primary_key(address_id))] +#[derive(Clone, Debug, Queryable, Identifiable, Selectable, Serialize, Deserialize)] +#[diesel(table_name = address, primary_key(address_id), check_for_backend(diesel::pg::Pg))] pub struct Address { pub id: Option<i32>, pub address_id: String, diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs index 7676e20d224..3b6de46e085 100644 --- a/crates/diesel_models/src/api_keys.rs +++ b/crates/diesel_models/src/api_keys.rs @@ -1,11 +1,13 @@ -use diesel::{AsChangeset, AsExpression, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, AsExpression, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::schema::api_keys; -#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Identifiable, Queryable)] -#[diesel(table_name = api_keys, primary_key(key_id))] +#[derive( + serde::Serialize, serde::Deserialize, Debug, Clone, Identifiable, Queryable, Selectable, +)] +#[diesel(table_name = api_keys, primary_key(key_id), check_for_backend(diesel::pg::Pg))] pub struct ApiKey { pub key_id: String, pub merchant_id: String, diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs index a94cbe96054..050bc291c0b 100644 --- a/crates/diesel_models/src/authentication.rs +++ b/crates/diesel_models/src/authentication.rs @@ -1,11 +1,13 @@ -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use serde_json; use crate::schema::authentication; -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = authentication, primary_key(authentication_id))] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, +)] +#[diesel(table_name = authentication, primary_key(authentication_id), check_for_backend(diesel::pg::Pg))] pub struct Authentication { pub authentication_id: String, pub merchant_id: String, diff --git a/crates/diesel_models/src/authorization.rs b/crates/diesel_models/src/authorization.rs index a7f13821d89..694577bba3f 100644 --- a/crates/diesel_models/src/authorization.rs +++ b/crates/diesel_models/src/authorization.rs @@ -1,13 +1,14 @@ use common_utils::types::MinorUnit; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::incremental_authorization}; -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Hash)] -#[diesel(table_name = incremental_authorization)] -#[diesel(primary_key(authorization_id, merchant_id))] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, Hash, +)] +#[diesel(table_name = incremental_authorization, primary_key(authorization_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct Authorization { pub authorization_id: String, pub merchant_id: String, diff --git a/crates/diesel_models/src/blocklist.rs b/crates/diesel_models/src/blocklist.rs index 9e88802aa3b..14dbaf2fe43 100644 --- a/crates/diesel_models/src/blocklist.rs +++ b/crates/diesel_models/src/blocklist.rs @@ -1,4 +1,4 @@ -use diesel::{Identifiable, Insertable, Queryable}; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist; @@ -13,8 +13,10 @@ pub struct BlocklistNew { pub created_at: time::PrimitiveDateTime, } -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Deserialize, Serialize)] -#[diesel(table_name = blocklist)] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, +)] +#[diesel(table_name = blocklist, check_for_backend(diesel::pg::Pg))] pub struct Blocklist { #[serde(skip)] pub id: i32, diff --git a/crates/diesel_models/src/blocklist_fingerprint.rs b/crates/diesel_models/src/blocklist_fingerprint.rs index e75856622e2..ceea5134bb3 100644 --- a/crates/diesel_models/src/blocklist_fingerprint.rs +++ b/crates/diesel_models/src/blocklist_fingerprint.rs @@ -1,4 +1,4 @@ -use diesel::{Identifiable, Insertable, Queryable}; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist_fingerprint; @@ -13,8 +13,10 @@ pub struct BlocklistFingerprintNew { pub created_at: time::PrimitiveDateTime, } -#[derive(Clone, Debug, Eq, PartialEq, Queryable, Identifiable, Deserialize, Serialize)] -#[diesel(table_name = blocklist_fingerprint)] +#[derive( + Clone, Debug, Eq, PartialEq, Queryable, Identifiable, Selectable, Deserialize, Serialize, +)] +#[diesel(table_name = blocklist_fingerprint, check_for_backend(diesel::pg::Pg))] pub struct BlocklistFingerprint { #[serde(skip_serializing)] pub id: i32, diff --git a/crates/diesel_models/src/blocklist_lookup.rs b/crates/diesel_models/src/blocklist_lookup.rs index ad2a893e03d..bebad02e780 100644 --- a/crates/diesel_models/src/blocklist_lookup.rs +++ b/crates/diesel_models/src/blocklist_lookup.rs @@ -1,4 +1,4 @@ -use diesel::{Identifiable, Insertable, Queryable}; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist_lookup; @@ -10,8 +10,19 @@ pub struct BlocklistLookupNew { pub fingerprint: String, } -#[derive(Default, Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Deserialize, Serialize)] -#[diesel(table_name = blocklist_lookup)] +#[derive( + Default, + Clone, + Debug, + Eq, + PartialEq, + Identifiable, + Queryable, + Selectable, + Deserialize, + Serialize, +)] +#[diesel(table_name = blocklist_lookup, check_for_backend(diesel::pg::Pg))] pub struct BlocklistLookup { #[serde(skip)] pub id: i32, diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 48eedc6110c..af343119060 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -1,5 +1,5 @@ use common_utils::pii; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::schema::business_profile; @@ -10,9 +10,10 @@ use crate::schema::business_profile; serde::Serialize, Identifiable, Queryable, + Selectable, router_derive::DebugAsDisplay, )] -#[diesel(table_name = business_profile, primary_key(profile_id))] +#[diesel(table_name = business_profile, primary_key(profile_id), check_for_backend(diesel::pg::Pg))] pub struct BusinessProfile { pub profile_id: String, pub merchant_id: String, diff --git a/crates/diesel_models/src/capture.rs b/crates/diesel_models/src/capture.rs index 0a66ae789aa..cff09638a40 100644 --- a/crates/diesel_models/src/capture.rs +++ b/crates/diesel_models/src/capture.rs @@ -1,13 +1,14 @@ use common_utils::types::MinorUnit; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::captures}; -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Hash)] -#[diesel(table_name = captures)] -#[diesel(primary_key(capture_id))] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, Hash, +)] +#[diesel(table_name = captures, primary_key(capture_id), check_for_backend(diesel::pg::Pg))] pub struct Capture { pub capture_id: String, pub payment_id: String, diff --git a/crates/diesel_models/src/cards_info.rs b/crates/diesel_models/src/cards_info.rs index 8f0a4af23af..3e0d24723d1 100644 --- a/crates/diesel_models/src/cards_info.rs +++ b/crates/diesel_models/src/cards_info.rs @@ -1,10 +1,12 @@ -use diesel::{Identifiable, Queryable}; +use diesel::{Identifiable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::cards_info}; -#[derive(Clone, Debug, Queryable, Identifiable, serde::Deserialize, serde::Serialize)] -#[diesel(table_name = cards_info, primary_key(card_iin))] +#[derive( + Clone, Debug, Queryable, Identifiable, Selectable, serde::Deserialize, serde::Serialize, +)] +#[diesel(table_name = cards_info, primary_key(card_iin), check_for_backend(diesel::pg::Pg))] pub struct CardInfo { pub card_iin: String, pub card_issuer: Option<String>, diff --git a/crates/diesel_models/src/configs.rs b/crates/diesel_models/src/configs.rs index 35fbb44647d..2b30aa6a972 100644 --- a/crates/diesel_models/src/configs.rs +++ b/crates/diesel_models/src/configs.rs @@ -1,6 +1,6 @@ use std::convert::From; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::configs; @@ -13,9 +13,8 @@ pub struct ConfigNew { pub config: String, } -#[derive(Default, Clone, Debug, Identifiable, Queryable, Deserialize, Serialize)] -#[diesel(table_name = configs)] - +#[derive(Default, Clone, Debug, Identifiable, Queryable, Selectable, Deserialize, Serialize)] +#[diesel(table_name = configs, check_for_backend(diesel::pg::Pg))] pub struct Config { #[serde(skip)] pub id: i32, diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index 63be0351a0c..deb1ac73f41 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -1,5 +1,5 @@ use common_utils::{id_type, pii}; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{encryption::Encryption, schema::customers}; @@ -52,8 +52,10 @@ impl From<CustomerNew> for Customer { } } -#[derive(Clone, Debug, Identifiable, Queryable, serde::Deserialize, serde::Serialize)] -#[diesel(table_name = customers)] +#[derive( + Clone, Debug, Identifiable, Queryable, Selectable, serde::Deserialize, serde::Serialize, +)] +#[diesel(table_name = customers, check_for_backend(diesel::pg::Pg))] pub struct Customer { pub id: i32, pub customer_id: id_type::CustomerId, diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs index eae8281a99d..184dce15641 100644 --- a/crates/diesel_models/src/dispute.rs +++ b/crates/diesel_models/src/dispute.rs @@ -1,5 +1,5 @@ use common_utils::custom_serde; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use serde::Serialize; use time::PrimitiveDateTime; @@ -32,8 +32,8 @@ pub struct DisputeNew { pub dispute_amount: i64, } -#[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable)] -#[diesel(table_name = dispute)] +#[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable, Selectable)] +#[diesel(table_name = dispute, check_for_backend(diesel::pg::Pg))] pub struct Dispute { #[serde(skip_serializing)] pub id: i32, @@ -83,7 +83,7 @@ pub enum DisputeUpdate { }, } -#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = dispute)] pub struct DisputeUpdateInternal { dispute_stage: Option<storage_enums::DisputeStage>, @@ -93,7 +93,7 @@ pub struct DisputeUpdateInternal { connector_reason_code: Option<String>, challenge_required_by: Option<PrimitiveDateTime>, connector_updated_at: Option<PrimitiveDateTime>, - modified_at: Option<PrimitiveDateTime>, + modified_at: PrimitiveDateTime, evidence: Option<Secret<serde_json::Value>>, } @@ -116,8 +116,8 @@ impl From<DisputeUpdate> for DisputeUpdateInternal { connector_reason_code, challenge_required_by, connector_updated_at, - modified_at: Some(common_utils::date_time::now()), - ..Default::default() + modified_at: common_utils::date_time::now(), + evidence: None, }, DisputeUpdate::StatusUpdate { dispute_status, @@ -125,12 +125,24 @@ impl From<DisputeUpdate> for DisputeUpdateInternal { } => Self { dispute_status: Some(dispute_status), connector_status, - modified_at: Some(common_utils::date_time::now()), - ..Default::default() + modified_at: common_utils::date_time::now(), + dispute_stage: None, + connector_reason: None, + connector_reason_code: None, + challenge_required_by: None, + connector_updated_at: None, + evidence: None, }, DisputeUpdate::EvidenceUpdate { evidence } => Self { evidence: Some(evidence), - ..Default::default() + dispute_stage: None, + dispute_status: None, + connector_status: None, + connector_reason: None, + connector_reason_code: None, + challenge_required_by: None, + connector_updated_at: None, + modified_at: common_utils::date_time::now(), }, } } diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs index fe87f307fb3..b3b1230441f 100644 --- a/crates/diesel_models/src/events.rs +++ b/crates/diesel_models/src/events.rs @@ -1,7 +1,6 @@ use common_utils::custom_serde; use diesel::{ - deserialize::FromSqlRow, expression::AsExpression, AsChangeset, Identifiable, Insertable, - Queryable, + expression::AsExpression, AsChangeset, Identifiable, Insertable, Queryable, Selectable, }; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -36,8 +35,8 @@ pub struct EventUpdateInternal { pub response: Option<Encryption>, } -#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable)] -#[diesel(table_name = events, primary_key(event_id))] +#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, Selectable)] +#[diesel(table_name = events, primary_key(event_id), check_for_backend(diesel::pg::Pg))] pub struct Event { pub event_id: String, pub event_type: storage_enums::EventType, @@ -60,7 +59,7 @@ pub struct Event { pub metadata: Option<EventMetadata>, } -#[derive(Clone, Debug, Deserialize, Serialize, AsExpression, FromSqlRow)] +#[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub enum EventMetadata { Payment { diff --git a/crates/diesel_models/src/file.rs b/crates/diesel_models/src/file.rs index 20150a6928d..af584323b92 100644 --- a/crates/diesel_models/src/file.rs +++ b/crates/diesel_models/src/file.rs @@ -1,5 +1,5 @@ use common_utils::custom_serde; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{Deserialize, Serialize}; use crate::schema::file_metadata; @@ -21,8 +21,8 @@ pub struct FileMetadataNew { pub merchant_connector_id: Option<String>, } -#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable)] -#[diesel(table_name = file_metadata, primary_key(file_id, merchant_id))] +#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, Selectable)] +#[diesel(table_name = file_metadata, primary_key(file_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FileMetadata { #[serde(skip_serializing)] pub file_id: String, diff --git a/crates/diesel_models/src/fraud_check.rs b/crates/diesel_models/src/fraud_check.rs index 5513afcfbd1..2cda6bbd7f5 100644 --- a/crates/diesel_models/src/fraud_check.rs +++ b/crates/diesel_models/src/fraud_check.rs @@ -1,5 +1,5 @@ use common_enums as storage_enums; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -7,8 +7,8 @@ use crate::{ enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, schema::fraud_check, }; -#[derive(Clone, Debug, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id))] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] +#[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FraudCheck { pub frm_id: String, pub payment_id: String, diff --git a/crates/diesel_models/src/generic_link.rs b/crates/diesel_models/src/generic_link.rs index b3e3da7a6d8..1017d2d47d4 100644 --- a/crates/diesel_models/src/generic_link.rs +++ b/crates/diesel_models/src/generic_link.rs @@ -5,16 +5,17 @@ use common_utils::{ PayoutLinkData, PayoutLinkStatus, }, }; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::{Duration, PrimitiveDateTime}; use crate::{enums as storage_enums, schema::generic_link}; -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = generic_link)] -#[diesel(primary_key(link_id))] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, +)] +#[diesel(table_name = generic_link, primary_key(link_id), check_for_backend(diesel::pg::Pg))] pub struct GenericLink { pub link_id: String, pub primary_reference: String, diff --git a/crates/diesel_models/src/gsm.rs b/crates/diesel_models/src/gsm.rs index 231f60bb251..6a444410fa8 100644 --- a/crates/diesel_models/src/gsm.rs +++ b/crates/diesel_models/src/gsm.rs @@ -4,7 +4,7 @@ use common_utils::{ custom_serde, events::{ApiEventMetric, ApiEventsType}, }; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::gateway_status_map; @@ -19,9 +19,10 @@ use crate::schema::gateway_status_map; router_derive::DebugAsDisplay, Identifiable, Queryable, + Selectable, serde::Serialize, )] -#[diesel(table_name = gateway_status_map, primary_key(connector, flow, sub_flow, code, message))] +#[diesel(table_name = gateway_status_map, primary_key(connector, flow, sub_flow, code, message), check_for_backend(diesel::pg::Pg))] pub struct GatewayStatusMap { pub connector: String, pub flow: String, diff --git a/crates/diesel_models/src/locker_mock_up.rs b/crates/diesel_models/src/locker_mock_up.rs index e078b272cba..e88ad95e236 100644 --- a/crates/diesel_models/src/locker_mock_up.rs +++ b/crates/diesel_models/src/locker_mock_up.rs @@ -1,10 +1,10 @@ use common_utils::id_type; -use diesel::{Identifiable, Insertable, Queryable}; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::locker_mock_up; -#[derive(Clone, Debug, Eq, Identifiable, Queryable, PartialEq)] -#[diesel(table_name = locker_mock_up)] +#[derive(Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq)] +#[diesel(table_name = locker_mock_up, check_for_backend(diesel::pg::Pg))] pub struct LockerMockUp { pub id: i32, pub card_id: String, diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs index 9a32e1049d5..793174dea71 100644 --- a/crates/diesel_models/src/mandate.rs +++ b/crates/diesel_models/src/mandate.rs @@ -1,13 +1,15 @@ use common_enums::MerchantStorageScheme; use common_utils::{id_type, pii}; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::mandate}; -#[derive(Clone, Debug, Identifiable, Queryable, serde::Serialize, serde::Deserialize)] -#[diesel(table_name = mandate)] +#[derive( + Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize, +)] +#[diesel(table_name = mandate, check_for_backend(diesel::pg::Pg))] pub struct Mandate { pub id: i32, pub mandate_id: String, diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index f0078ca0ba1..71c437bbb41 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -1,5 +1,5 @@ use common_utils::pii; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_account}; @@ -10,9 +10,10 @@ use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_acc serde::Serialize, Identifiable, Queryable, + Selectable, router_derive::DebugAsDisplay, )] -#[diesel(table_name = merchant_account)] +#[diesel(table_name = merchant_account, check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { pub id: i32, pub merchant_id: String, diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index 680e3dacc85..6f907b1d607 100644 --- a/crates/diesel_models/src/merchant_connector_account.rs +++ b/crates/diesel_models/src/merchant_connector_account.rs @@ -1,7 +1,7 @@ use std::fmt::Debug; use common_utils::pii; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_connector_account}; @@ -13,9 +13,10 @@ use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_con serde::Deserialize, Identifiable, Queryable, + Selectable, router_derive::DebugAsDisplay, )] -#[diesel(table_name = merchant_connector_account)] +#[diesel(table_name = merchant_connector_account, check_for_backend(diesel::pg::Pg))] pub struct MerchantConnectorAccount { pub id: i32, pub merchant_id: String, diff --git a/crates/diesel_models/src/merchant_key_store.rs b/crates/diesel_models/src/merchant_key_store.rs index ef17ace1491..30781927e94 100644 --- a/crates/diesel_models/src/merchant_key_store.rs +++ b/crates/diesel_models/src/merchant_key_store.rs @@ -1,5 +1,5 @@ use common_utils::custom_serde; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{encryption::Encryption, schema::merchant_key_store}; @@ -11,10 +11,10 @@ use crate::{encryption::Encryption, schema::merchant_key_store}; serde::Deserialize, Identifiable, Queryable, + Selectable, router_derive::DebugAsDisplay, )] -#[diesel(table_name = merchant_key_store)] -#[diesel(primary_key(merchant_id))] +#[diesel(table_name = merchant_key_store, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantKeyStore { pub merchant_id: String, pub key: Encryption, diff --git a/crates/diesel_models/src/organization.rs b/crates/diesel_models/src/organization.rs index 2f407b8cbfd..5c2012a6d9a 100644 --- a/crates/diesel_models/src/organization.rs +++ b/crates/diesel_models/src/organization.rs @@ -1,9 +1,9 @@ -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::schema::organization; -#[derive(Clone, Debug, Identifiable, Queryable)] -#[diesel(table_name = organization, primary_key(org_id))] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable)] +#[diesel(table_name = organization, primary_key(org_id), check_for_backend(diesel::pg::Pg))] pub struct Organization { pub org_id: String, pub org_name: Option<String>, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index c45eee7b0ce..626de947102 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -1,5 +1,5 @@ use common_utils::pii; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -8,8 +8,10 @@ use crate::{ schema::payment_attempt, }; -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id))] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, +)] +#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentAttempt { pub payment_id: String, pub merchant_id: String, @@ -92,9 +94,7 @@ pub struct PaymentListFilters { pub payment_method: Vec<storage_enums::PaymentMethod>, } -#[derive( - Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, -)] +#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptNew { pub payment_id: String, @@ -117,10 +117,10 @@ pub struct PaymentAttemptNew { pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub created_at: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub modified_at: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, @@ -366,7 +366,7 @@ pub enum PaymentAttemptUpdate { }, } -#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptUpdateInternal { amount: Option<i64>, @@ -381,7 +381,7 @@ pub struct PaymentAttemptUpdateInternal { error_message: Option<Option<String>>, payment_method_id: Option<String>, cancellation_reason: Option<String>, - modified_at: Option<PrimitiveDateTime>, + modified_at: PrimitiveDateTime, mandate_id: Option<String>, browser_info: Option<serde_json::Value>, payment_token: Option<String>, @@ -571,7 +571,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { authentication_type, payment_method, payment_token, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), payment_method_data, payment_method_type, payment_experience, @@ -583,16 +583,85 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { fingerprint_id, payment_method_billing_address_id, updated_by, - ..Default::default() + net_amount: None, + connector_transaction_id: None, + connector: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + error_code: None, + connector_metadata: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + connector_response_reference_id: None, + multiple_capture_count: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type, updated_by, } => Self { authentication_type: Some(authentication_type), - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::ConfirmUpdate { amount, @@ -631,7 +700,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { authentication_type, status: Some(status), payment_method, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), browser_info, connector: connector.map(Some), payment_token, @@ -657,7 +726,21 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { client_source, client_version, customer_acceptance, - ..Default::default() + net_amount: None, + connector_transaction_id: None, + amount_to_capture: None, + cancellation_reason: None, + mandate_id: None, + connector_metadata: None, + preprocessing_step_id: None, + error_reason: None, + connector_response_reference_id: None, + multiple_capture_count: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + charge_id: None, }, PaymentAttemptUpdate::VoidUpdate { status, @@ -666,8 +749,50 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { } => Self { status: Some(status), cancellation_reason, + modified_at: common_utils::date_time::now(), updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::RejectUpdate { status, @@ -676,10 +801,51 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, } => Self { status: Some(status), + modified_at: common_utils::date_time::now(), error_code, error_message, updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::BlocklistUpdate { status, @@ -688,20 +854,102 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, } => Self { status: Some(status), + modified_at: common_utils::date_time::now(), error_code, connector: Some(None), error_message, updated_by, merchant_connector_id: Some(None), - ..Default::default() + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + authentication_type: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, updated_by, } => Self { payment_method_id, + modified_at: common_utils::date_time::now(), updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::ResponseUpdate { status, @@ -730,7 +978,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, authentication_type, payment_method_id, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), mandate_id, connector_metadata, error_code, @@ -746,7 +994,31 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_message, payment_method_data, charge_id, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + amount_to_capture: None, + payment_method: None, + cancellation_reason: None, + browser_info: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + merchant_connector_id: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::ErrorUpdate { connector, @@ -766,7 +1038,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { status: Some(status), error_message, error_code, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), error_reason, amount_capturable, updated_by, @@ -775,12 +1047,87 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, payment_method_data, authentication_type, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + amount_to_capture: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self { status: Some(status), + modified_at: common_utils::date_time::now(), updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::UpdateTrackers { payment_token, @@ -793,6 +1140,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { merchant_connector_id, } => Self { payment_token, + modified_at: common_utils::date_time::now(), connector: connector.map(Some), straight_through_algorithm, amount_capturable, @@ -800,7 +1148,43 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { tax_amount, updated_by, merchant_connector_id: merchant_connector_id.map(Some), - ..Default::default() + amount: None, + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + amount_to_capture: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::UnresolvedResponseUpdate { status, @@ -817,13 +1201,48 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector: connector.map(Some), connector_transaction_id, payment_method_id, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), error_code, error_message, error_reason, connector_response_reference_id, updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + amount_to_capture: None, + authentication_type: None, + payment_method: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::PreprocessingUpdate { status, @@ -836,13 +1255,50 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { } => Self { status: Some(status), payment_method_id, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), connector_metadata, preprocessing_step_id, connector_transaction_id, connector_response_reference_id, updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + error_reason: None, + capture_method: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::CaptureUpdate { multiple_capture_count, @@ -850,9 +1306,51 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { amount_to_capture, } => Self { multiple_capture_count, + modified_at: common_utils::date_time::now(), updated_by, amount_to_capture, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::AmountToCaptureUpdate { status, @@ -860,9 +1358,51 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, } => Self { status: Some(status), + modified_at: common_utils::date_time::now(), amount_capturable: Some(amount_capturable), updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::ConnectorResponse { authentication_data, @@ -876,17 +1416,99 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { encoded_data, connector_transaction_id, connector: connector.map(Some), + modified_at: common_utils::date_time::now(), updated_by, charge_id, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + status: None, + amount_to_capture: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { amount, amount_capturable, } => Self { amount: Some(amount), + modified_at: common_utils::date_time::now(), amount_capturable: Some(amount_capturable), - ..Default::default() + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + updated_by: String::default(), + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::AuthenticationUpdate { status, @@ -896,11 +1518,51 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, } => Self { status: Some(status), + modified_at: common_utils::date_time::now(), external_three_ds_authentication_attempted, authentication_connector, authentication_id, updated_by, - ..Default::default() + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, PaymentAttemptUpdate::ManualUpdate { status, @@ -913,12 +1575,50 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { } => Self { status, error_code: error_code.map(Some), + modified_at: common_utils::date_time::now(), error_message: error_message.map(Some), error_reason: error_reason.map(Some), updated_by, unified_code: unified_code.map(Some), unified_message: unified_message.map(Some), - ..Default::default() + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }, } } diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 0272f8fec14..8deca44253a 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -1,13 +1,13 @@ use common_enums::RequestIncrementalAuthorization; use common_utils::{id_type, pii, types::MinorUnit}; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{encryption::Encryption, enums as storage_enums, schema::payment_intent}; -#[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id))] +#[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize)] +#[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub payment_id: String, pub merchant_id: String, @@ -85,10 +85,10 @@ pub struct PaymentIntentNew { pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub created_at: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub modified_at: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, @@ -228,7 +228,7 @@ pub struct PaymentIntentUpdateFields { pub shipping_details: Option<Encryption>, } -#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, @@ -242,7 +242,7 @@ pub struct PaymentIntentUpdateInternal { pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, - pub modified_at: Option<PrimitiveDateTime>, + pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, @@ -360,9 +360,39 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { updated_by, } => Self { metadata: Some(metadata), - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), updated_by, - ..Default::default() + amount: None, + currency: None, + status: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + billing_address_id: None, + shipping_address_id: None, + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::Update(value) => Self { amount: Some(value.amount), @@ -391,7 +421,15 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { billing_details: value.billing_details, merchant_order_reference_id: value.merchant_order_reference_id, shipping_details: value.shipping_details, - ..Default::default() + amount_captured: None, + off_session: None, + modified_at: common_utils::date_time::now(), + active_attempt_id: None, + attempt_count: None, + merchant_decision: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, }, PaymentIntentUpdate::PaymentCreateUpdate { return_url, @@ -408,9 +446,34 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { shipping_address_id, billing_address_id, customer_details, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), updated_by, - ..Default::default() + amount: None, + currency: None, + amount_captured: None, + setup_future_usage: None, + off_session: None, + metadata: None, + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::PGStatusUpdate { status, @@ -418,10 +481,39 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { incremental_authorization_allowed, } => Self { status: Some(status), - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, - ..Default::default() + amount: None, + currency: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + surcharge_applicable: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::MerchantStatusUpdate { status, @@ -432,9 +524,37 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { status: Some(status), shipping_address_id, billing_address_id, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), updated_by, - ..Default::default() + amount: None, + currency: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::ResponseUpdate { // amount, @@ -454,10 +574,36 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fingerprint_id, // customer_id, return_url, - modified_at: Some(common_utils::date_time::now()), + modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, - ..Default::default() + amount: None, + currency: None, + customer_id: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + surcharge_applicable: None, + authorization_count: None, + session_expiry: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, @@ -467,7 +613,37 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, - ..Default::default() + amount: None, + currency: None, + status: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + modified_at: common_utils::date_time::now(), + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + merchant_decision: None, + payment_confirm_source: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::StatusAndAttemptUpdate { status, @@ -479,7 +655,36 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, - ..Default::default() + amount: None, + currency: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + modified_at: common_utils::date_time::now(), + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + merchant_decision: None, + payment_confirm_source: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::ApproveUpdate { status, @@ -489,7 +694,37 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { status: Some(status), merchant_decision, updated_by, - ..Default::default() + amount: None, + currency: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + modified_at: common_utils::date_time::now(), + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + payment_confirm_source: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::RejectUpdate { status, @@ -499,7 +734,37 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { status: Some(status), merchant_decision, updated_by, - ..Default::default() + amount: None, + currency: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + modified_at: common_utils::date_time::now(), + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + payment_confirm_source: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable, @@ -507,28 +772,186 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { } => Self { surcharge_applicable, updated_by, - ..Default::default() + amount: None, + currency: None, + status: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + modified_at: common_utils::date_time::now(), + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self { amount: Some(amount), - ..Default::default() + currency: None, + status: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + modified_at: common_utils::date_time::now(), + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + updated_by: String::default(), + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, } => Self { authorization_count: Some(authorization_count), - ..Default::default() + amount: None, + currency: None, + status: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + modified_at: common_utils::date_time::now(), + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + updated_by: String::default(), + surcharge_applicable: None, + incremental_authorization_allowed: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id, } => Self { shipping_address_id, - ..Default::default() + amount: None, + currency: None, + status: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + modified_at: common_utils::date_time::now(), + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + updated_by: String::default(), + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { status, updated_by, - ..Default::default() + amount: None, + currency: None, + amount_captured: None, + customer_id: None, + return_url: None, + setup_future_usage: None, + off_session: None, + metadata: None, + billing_address_id: None, + shipping_address_id: None, + modified_at: common_utils::date_time::now(), + active_attempt_id: None, + business_country: None, + business_label: None, + description: None, + statement_descriptor_name: None, + statement_descriptor_suffix: None, + order_details: None, + attempt_count: None, + merchant_decision: None, + payment_confirm_source: None, + surcharge_applicable: None, + incremental_authorization_allowed: None, + authorization_count: None, + session_expiry: None, + fingerprint_id: None, + request_external_three_ds_authentication: None, + frm_metadata: None, + customer_details: None, + billing_details: None, + merchant_order_reference_id: None, + shipping_details: None, }, } } diff --git a/crates/diesel_models/src/payment_link.rs b/crates/diesel_models/src/payment_link.rs index f4630c75d72..7937d2fbe30 100644 --- a/crates/diesel_models/src/payment_link.rs +++ b/crates/diesel_models/src/payment_link.rs @@ -1,13 +1,12 @@ use common_utils::types::MinorUnit; -use diesel::{Identifiable, Insertable, Queryable}; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payment_link}; -#[derive(Clone, Debug, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = payment_link)] -#[diesel(primary_key(payment_link_id))] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] +#[diesel(table_name = payment_link, primary_key(payment_link_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentLink { pub payment_link_id: String, pub payment_id: String, diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 16e8ddeb7d5..a9db90abb20 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -1,14 +1,16 @@ use common_enums::MerchantStorageScheme; use common_utils::{id_type, pii}; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{encryption::Encryption, enums as storage_enums, schema::payment_methods}; -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = payment_methods)] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, +)] +#[diesel(table_name = payment_methods, check_for_backend(diesel::pg::Pg))] pub struct PaymentMethod { pub id: i32, pub customer_id: id_type::CustomerId, diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rs index 68c99d5ac08..9eb2a5a59db 100644 --- a/crates/diesel_models/src/payout_attempt.rs +++ b/crates/diesel_models/src/payout_attempt.rs @@ -1,13 +1,14 @@ use common_utils::id_type; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payout_attempt}; -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = payout_attempt)] -#[diesel(primary_key(payout_attempt_id))] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, +)] +#[diesel(table_name = payout_attempt, primary_key(payout_attempt_id), check_for_backend(diesel::pg::Pg))] pub struct PayoutAttempt { pub payout_attempt_id: String, pub payout_id: String, diff --git a/crates/diesel_models/src/payouts.rs b/crates/diesel_models/src/payouts.rs index 5cb06d7755b..acef00b15d2 100644 --- a/crates/diesel_models/src/payouts.rs +++ b/crates/diesel_models/src/payouts.rs @@ -1,14 +1,15 @@ use common_utils::{id_type, pii, types::MinorUnit}; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payouts}; // Payouts -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = payouts)] -#[diesel(primary_key(payout_id))] +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, +)] +#[diesel(table_name = payouts, primary_key(payout_id), check_for_backend(diesel::pg::Pg))] pub struct Payouts { pub payout_id: String, pub merchant_id: String, @@ -66,10 +67,10 @@ pub struct PayoutsNew { pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub created_at: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub last_modified_at: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: String, pub status: storage_enums::PayoutStatus, diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 342ad8453af..cd2c429c55e 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -1,5 +1,5 @@ use common_utils::ext_traits::Encode; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -14,10 +14,11 @@ use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResu Deserialize, Identifiable, Queryable, + Selectable, Serialize, router_derive::DebugAsDisplay, )] -#[diesel(table_name = process_tracker)] +#[diesel(table_name = process_tracker, check_for_backend(diesel::pg::Pg))] pub struct ProcessTracker { pub id: String, pub name: Option<String>, diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index 44d6133d8fb..a3e767fdb32 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -2,16 +2,24 @@ use common_utils::{ pii, types::{ChargeRefunds, MinorUnit}, }; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::refund}; #[derive( - Clone, Debug, Eq, Identifiable, Queryable, PartialEq, serde::Serialize, serde::Deserialize, + Clone, + Debug, + Eq, + Identifiable, + Queryable, + Selectable, + PartialEq, + serde::Serialize, + serde::Deserialize, )] -#[diesel(table_name = refund)] +#[diesel(table_name = refund, check_for_backend(diesel::pg::Pg))] pub struct Refund { pub id: i32, pub internal_reference_id: String, @@ -34,7 +42,7 @@ pub struct Refund { #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] - pub updated_at: PrimitiveDateTime, + pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, pub refund_reason: Option<String>, @@ -48,7 +56,6 @@ pub struct Refund { #[derive( Clone, Debug, - Default, Eq, PartialEq, Insertable, @@ -75,10 +82,10 @@ pub struct RefundNew { pub sent_to_gateway: bool, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub created_at: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub modified_at: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, pub refund_reason: Option<String>, @@ -88,6 +95,38 @@ pub struct RefundNew { pub charges: Option<ChargeRefunds>, } +impl Default for RefundNew { + fn default() -> Self { + Self { + refund_id: Default::default(), + payment_id: Default::default(), + merchant_id: Default::default(), + internal_reference_id: Default::default(), + external_reference_id: Default::default(), + connector_transaction_id: Default::default(), + connector: Default::default(), + connector_refund_id: Default::default(), + refund_type: Default::default(), + total_amount: Default::default(), + currency: Default::default(), + refund_amount: Default::default(), + refund_status: Default::default(), + sent_to_gateway: Default::default(), + metadata: Default::default(), + refund_arn: Default::default(), + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + description: Default::default(), + attempt_id: Default::default(), + refund_reason: Default::default(), + profile_id: Default::default(), + updated_by: Default::default(), + merchant_connector_id: Default::default(), + charges: Default::default(), + } + } +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { @@ -124,7 +163,7 @@ pub enum RefundUpdate { }, } -#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { connector_refund_id: Option<String>, @@ -136,6 +175,7 @@ pub struct RefundUpdateInternal { refund_reason: Option<String>, refund_error_code: Option<String>, updated_by: String, + modified_at: PrimitiveDateTime, } impl RefundUpdateInternal { @@ -150,6 +190,7 @@ impl RefundUpdateInternal { refund_reason: self.refund_reason, refund_error_code: self.refund_error_code, updated_by: self.updated_by, + modified_at: self.modified_at, ..source } } @@ -172,7 +213,10 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_message, refund_arn: Some(refund_arn), updated_by, - ..Default::default() + metadata: None, + refund_reason: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), }, RefundUpdate::MetadataAndReasonUpdate { metadata, @@ -182,7 +226,13 @@ impl From<RefundUpdate> for RefundUpdateInternal { metadata, refund_reason: reason, updated_by, - ..Default::default() + connector_refund_id: None, + refund_status: None, + sent_to_gateway: None, + refund_error_message: None, + refund_arn: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), }, RefundUpdate::StatusUpdate { connector_refund_id, @@ -194,7 +244,12 @@ impl From<RefundUpdate> for RefundUpdateInternal { sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, - ..Default::default() + refund_error_message: None, + refund_arn: None, + metadata: None, + refund_reason: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), }, RefundUpdate::ErrorUpdate { refund_status, @@ -208,7 +263,11 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_code, updated_by, connector_refund_id, - ..Default::default() + sent_to_gateway: None, + refund_arn: None, + metadata: None, + refund_reason: None, + modified_at: common_utils::date_time::now(), }, RefundUpdate::ManualUpdate { refund_status, @@ -220,7 +279,12 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_message, refund_error_code, updated_by, - ..Default::default() + connector_refund_id: None, + sent_to_gateway: None, + refund_arn: None, + metadata: None, + refund_reason: None, + modified_at: common_utils::date_time::now(), }, } } @@ -238,6 +302,7 @@ impl RefundUpdate { refund_reason, refund_error_code, updated_by, + modified_at: _, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), @@ -249,6 +314,7 @@ impl RefundUpdate { metadata: metadata.or(source.metadata), refund_reason: refund_reason.or(source.refund_reason), updated_by, + modified_at: common_utils::date_time::now(), ..source } } diff --git a/crates/diesel_models/src/reverse_lookup.rs b/crates/diesel_models/src/reverse_lookup.rs index a9463d27b63..87fca344078 100644 --- a/crates/diesel_models/src/reverse_lookup.rs +++ b/crates/diesel_models/src/reverse_lookup.rs @@ -1,4 +1,4 @@ -use diesel::{Identifiable, Insertable, Queryable}; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::reverse_lookup; @@ -6,10 +6,17 @@ use crate::schema::reverse_lookup; /// This reverse lookup table basically looks up id's and get result_id that you want. This is /// useful for KV where you can't lookup without key #[derive( - Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Eq, PartialEq, + Clone, + Debug, + serde::Serialize, + serde::Deserialize, + Identifiable, + Queryable, + Selectable, + Eq, + PartialEq, )] -#[diesel(table_name = reverse_lookup)] -#[diesel(primary_key(lookup_id))] +#[diesel(table_name = reverse_lookup, primary_key(lookup_id), check_for_backend(diesel::pg::Pg))] pub struct ReverseLookup { /// Primary key. The key id. pub lookup_id: String, diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs index 075d0602554..b5b80628039 100644 --- a/crates/diesel_models/src/role.rs +++ b/crates/diesel_models/src/role.rs @@ -1,10 +1,10 @@ -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::roles}; -#[derive(Clone, Debug, Identifiable, Queryable)] -#[diesel(table_name = roles)] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable)] +#[diesel(table_name = roles, check_for_backend(diesel::pg::Pg))] pub struct Role { pub id: i32, pub role_name: String, diff --git a/crates/diesel_models/src/routing_algorithm.rs b/crates/diesel_models/src/routing_algorithm.rs index 11e80f29daf..4634dd1af49 100644 --- a/crates/diesel_models/src/routing_algorithm.rs +++ b/crates/diesel_models/src/routing_algorithm.rs @@ -1,10 +1,10 @@ -use diesel::{Identifiable, Insertable, Queryable}; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::{enums, schema::routing_algorithm}; -#[derive(Clone, Debug, Identifiable, Insertable, Queryable, Serialize, Deserialize)] -#[diesel(table_name = routing_algorithm, primary_key(algorithm_id))] +#[derive(Clone, Debug, Identifiable, Insertable, Queryable, Selectable, Serialize, Deserialize)] +#[diesel(table_name = routing_algorithm, primary_key(algorithm_id), check_for_backend(diesel::pg::Pg))] pub struct RoutingAlgorithm { pub algorithm_id: String, pub profile_id: String, diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index b1bbb66256c..56c6f00f2b0 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -1,5 +1,5 @@ use common_utils::pii; -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; @@ -10,8 +10,8 @@ use crate::{ pub mod dashboard_metadata; pub mod sample_data; -#[derive(Clone, Debug, Identifiable, Queryable)] -#[diesel(table_name = users)] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable)] +#[diesel(table_name = users, check_for_backend(diesel::pg::Pg))] pub struct User { pub id: i32, pub user_id: String, diff --git a/crates/diesel_models/src/user/dashboard_metadata.rs b/crates/diesel_models/src/user/dashboard_metadata.rs index 48028ba6b5f..a01f88fcb12 100644 --- a/crates/diesel_models/src/user/dashboard_metadata.rs +++ b/crates/diesel_models/src/user/dashboard_metadata.rs @@ -1,10 +1,10 @@ -use diesel::{query_builder::AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{query_builder::AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::dashboard_metadata}; -#[derive(Clone, Debug, Identifiable, Queryable)] -#[diesel(table_name = dashboard_metadata)] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable)] +#[diesel(table_name = dashboard_metadata, check_for_backend(diesel::pg::Pg))] pub struct DashboardMetadata { pub id: i32, pub user_id: Option<String>, diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 1d9cd87ad4e..7a0f00acf83 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -12,7 +12,7 @@ use crate::{ }; #[derive( - Clone, Debug, Default, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, + Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptBatchNew { @@ -35,10 +35,10 @@ pub struct PaymentAttemptBatchNew { pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<AuthenticationType>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub created_at: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub modified_at: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, diff --git a/crates/diesel_models/src/user_authentication_method.rs b/crates/diesel_models/src/user_authentication_method.rs index 2b4ed23c1d8..18a65b9f104 100644 --- a/crates/diesel_models/src/user_authentication_method.rs +++ b/crates/diesel_models/src/user_authentication_method.rs @@ -1,10 +1,10 @@ -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{encryption::Encryption, enums, schema::user_authentication_methods}; -#[derive(Clone, Debug, Identifiable, Queryable)] -#[diesel(table_name = user_authentication_methods)] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable)] +#[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))] pub struct UserAuthenticationMethod { pub id: String, pub auth_id: String, diff --git a/crates/diesel_models/src/user_key_store.rs b/crates/diesel_models/src/user_key_store.rs index a35b4d9d169..1b19ef31a49 100644 --- a/crates/diesel_models/src/user_key_store.rs +++ b/crates/diesel_models/src/user_key_store.rs @@ -1,11 +1,12 @@ -use diesel::{Identifiable, Insertable, Queryable}; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{encryption::Encryption, schema::user_key_store}; -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable)] -#[diesel(table_name = user_key_store)] -#[diesel(primary_key(user_id))] +#[derive( + Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, +)] +#[diesel(table_name = user_key_store, primary_key(user_id), check_for_backend(diesel::pg::Pg))] pub struct UserKeyStore { pub user_id: String, pub key: Encryption, diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs index 3c32092fa91..ea8b626358e 100644 --- a/crates/diesel_models/src/user_role.rs +++ b/crates/diesel_models/src/user_role.rs @@ -1,10 +1,10 @@ -use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::user_roles}; -#[derive(Clone, Debug, Identifiable, Queryable)] -#[diesel(table_name = user_roles)] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable)] +#[diesel(table_name = user_roles, check_for_backend(diesel::pg::Pg))] pub struct UserRole { pub id: i32, pub user_id: String, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index e7ccd6f33a6..fb8ce2d6966 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -632,8 +632,8 @@ impl behaviour::Conversion for PaymentIntent { billing_address_id: self.billing_address_id, statement_descriptor_name: self.statement_descriptor_name, statement_descriptor_suffix: self.statement_descriptor_suffix, - created_at: Some(self.created_at), - modified_at: Some(self.modified_at), + created_at: self.created_at, + modified_at: self.modified_at, last_synced: self.last_synced, setup_future_usage: self.setup_future_usage, off_session: self.off_session, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index dc801e37546..6eb35616729 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -630,7 +630,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal { fn from(value: PaymentIntentUpdateInternal) -> Self { - let modified_at = Some(common_utils::date_time::now()); + let modified_at = common_utils::date_time::now(); let PaymentIntentUpdateInternal { amount, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index cf45f077295..5b74eefb9a4 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -804,8 +804,8 @@ pub async fn validate_and_create_refund( .set_total_amount(payment_attempt.amount) .set_refund_amount(refund_amount) .set_currency(currency) - .set_created_at(Some(common_utils::date_time::now())) - .set_modified_at(Some(common_utils::date_time::now())) + .set_created_at(common_utils::date_time::now()) + .set_modified_at(common_utils::date_time::now()) .set_refund_status(enums::RefundStatus::Pending) .set_metadata(req.metadata) .set_description(req.reason.clone()) @@ -1030,7 +1030,7 @@ impl ForeignFrom<storage::Refund> for api::RefundResponse { error_message: refund.refund_error_message, error_code: refund.refund_error_code, created_at: Some(refund.created_at), - updated_at: Some(refund.updated_at), + updated_at: Some(refund.modified_at), connector: refund.connector, merchant_connector_id: refund.merchant_connector_id, charges: refund.charges, diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index c5edd863caf..a36af014710 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -273,7 +273,7 @@ mod storage { #[cfg(feature = "kv_store")] mod storage { - use common_utils::{date_time, ext_traits::Encode, fallback_reverse_lookup_not_found}; + use common_utils::{ext_traits::Encode, fallback_reverse_lookup_not_found}; use error_stack::{report, ResultExt}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; @@ -389,8 +389,8 @@ mod storage { refund_error_code: None, metadata: new.metadata.clone(), refund_arn: new.refund_arn.clone(), - created_at: new.created_at.unwrap_or_else(date_time::now), - updated_at: new.created_at.unwrap_or_else(date_time::now), + created_at: new.created_at, + modified_at: new.created_at, description: new.description.clone(), refund_reason: new.refund_reason.clone(), profile_id: new.profile_id.clone(), @@ -844,8 +844,8 @@ impl RefundInterface for MockDb { refund_error_code: None, metadata: new.metadata, refund_arn: new.refund_arn.clone(), - created_at: new.created_at.unwrap_or(current_time), - updated_at: current_time, + created_at: new.created_at, + modified_at: current_time, description: new.description, refund_reason: new.refund_reason.clone(), profile_id: new.profile_id, diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs index d5ef71bf651..14b317b52ea 100644 --- a/crates/router/src/services/kafka/refund.rs +++ b/crates/router/src/services/kafka/refund.rs @@ -50,7 +50,7 @@ impl<'a> KafkaRefund<'a> { refund_error_message: refund.refund_error_message.as_ref(), refund_arn: refund.refund_arn.as_ref(), created_at: refund.created_at.assume_utc(), - modified_at: refund.updated_at.assume_utc(), + modified_at: refund.modified_at.assume_utc(), description: refund.description.as_ref(), attempt_id: &refund.attempt_id, refund_reason: refund.refund_reason.as_ref(), diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index 6aa80b243c1..fea0b8c45e7 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -51,7 +51,7 @@ impl<'a> KafkaRefundEvent<'a> { refund_error_message: refund.refund_error_message.as_ref(), refund_arn: refund.refund_arn.as_ref(), created_at: refund.created_at.assume_utc(), - modified_at: refund.updated_at.assume_utc(), + modified_at: refund.modified_at.assume_utc(), description: refund.description.as_ref(), attempt_id: &refund.attempt_id, refund_reason: refund.refund_reason.as_ref(), diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 4a6c76aab74..b817d3e1cd7 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -263,14 +263,49 @@ pub async fn generate_sample_data( _ => None, }, confirm: true, - created_at: Some(created_at), - modified_at: Some(modified_at), + created_at, + modified_at, last_synced: Some(last_synced), amount_to_capture: Some(amount * 100), connector_response_reference_id: Some(attempt_id.clone()), updated_by: merchant_from_db.storage_scheme.to_string(), - - ..Default::default() + save_to_locker: None, + offer_amount: None, + surcharge_amount: None, + tax_amount: None, + payment_method_id: None, + capture_method: None, + capture_on: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_experience: None, + payment_method_data: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + mandate_details: None, + error_reason: None, + multiple_capture_count: None, + amount_capturable: i64::default(), + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + net_amount: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + mandate_data: None, + payment_method_billing_address_id: None, + fingerprint_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { @@ -285,8 +320,8 @@ pub async fn generate_sample_data( connector_transaction_id: attempt_id.clone(), connector_refund_id: None, description: Some("This is a sample refund".to_string()), - created_at: Some(created_at), - modified_at: Some(modified_at), + created_at, + modified_at, refund_reason: Some("Sample Refund".to_string()), connector: payment_attempt .connector diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 7a56cae1741..a5b1e902593 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1303,8 +1303,10 @@ impl DataModelExt for PaymentAttemptNew { capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, - created_at: self.created_at, - modified_at: self.modified_at, + created_at: self.created_at.unwrap_or_else(common_utils::date_time::now), + modified_at: self + .modified_at + .unwrap_or_else(common_utils::date_time::now), last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self @@ -1367,8 +1369,8 @@ impl DataModelExt for PaymentAttemptNew { capture_on: storage_model.capture_on, confirm: storage_model.confirm, authentication_type: storage_model.authentication_type, - created_at: storage_model.created_at, - modified_at: storage_model.modified_at, + created_at: Some(storage_model.created_at), + modified_at: Some(storage_model.modified_at), last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, amount_to_capture: storage_model.amount_to_capture.map(MinorUnit::new), diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index 69005a27a8b..7a9dba0f20b 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -746,8 +746,10 @@ impl DataModelExt for PayoutsNew { return_url: self.return_url, entity_type: self.entity_type, metadata: self.metadata, - created_at: self.created_at, - last_modified_at: self.last_modified_at, + created_at: self.created_at.unwrap_or_else(common_utils::date_time::now), + last_modified_at: self + .last_modified_at + .unwrap_or_else(common_utils::date_time::now), profile_id: self.profile_id, status: self.status, attempt_count: self.attempt_count, @@ -775,8 +777,8 @@ impl DataModelExt for PayoutsNew { return_url: storage_model.return_url, entity_type: storage_model.entity_type, metadata: storage_model.metadata, - created_at: storage_model.created_at, - last_modified_at: storage_model.last_modified_at, + created_at: Some(storage_model.created_at), + last_modified_at: Some(storage_model.last_modified_at), profile_id: storage_model.profile_id, status: storage_model.status, attempt_count: storage_model.attempt_count,
2024-07-12T12:14:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> `modified_at` field is now updated at every state change for: - Payment Attempts - Payment Intents - Refunds - Disputes - Payouts ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Just do a Payment Create and Payment Update (or any other kind of update as well to the payment), `modified_at` may get updated at every update curls: Payment create: ```bash curl --location 'http://localhost:8080/payments/pay_mn0Jew5RpmZRG2K1QysX' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_IG9ateOUhGE0KLFEItNN1tsJXcr5M62N7zlbtOlUtStTfPpzSomswbQa4aO2k1B4' \ --data-raw '{ "amount": 20000, "currency": "SGD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "email": "joseph@example.com", "name": "joseph Doe", "phone": "9123456789", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "return_url": "https://duck.com", "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": "John", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Payment Update: ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_IG9ateOUhGE0KLFEItNN1tsJXcr5M62N7zlbtOlUtStTfPpzSomswbQa4aO2k1B4' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "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": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.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": "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" }, "phone": { "number": "9123456789", "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": "9123456789", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "stripe" } }' ``` <img width="922" alt="Screenshot 2024-07-16 at 3 41 29 PM" src="https://github.com/user-attachments/assets/e1b2f3a8-5998-44e6-9a1f-d607a63b07ea"> <img width="937" alt="Screenshot 2024-07-16 at 3 41 36 PM" src="https://github.com/user-attachments/assets/a15d8464-9720-4175-ba20-ac729e871fbf"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e0b6cbb229f64be7a846b3c1573a6c6f8151b47b
juspay/hyperswitch
juspay__hyperswitch-5245
Bug: [BUG]: [Adyen] Remove payment_method_type as required field in MIT ### Bug Description Currently payment_method_type is a required field in MIT payments, which might not be the case all the time, so we need to handle this scenario ### Expected Behavior MIT payments should work regardless payment_method_type was provided or not ### Actual Behavior Currently payment_method_type is a required field in MIT payments, which might not be the case all the time, so we need to handle this scenario ### 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/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index d320475e61c..d56ec571ac6 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2528,16 +2528,14 @@ impl<'a> let browser_info = None; let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_return_url()?; - let payment_method_type = item - .router_data - .request - .payment_method_type - .as_ref() - .ok_or(errors::ConnectorError::MissingPaymentMethodType)?; + let payment_method_type = item.router_data.request.payment_method_type; let payment_method = match mandate_ref_id { payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => { let adyen_mandate = AdyenMandate { - payment_type: PaymentType::try_from(payment_method_type)?, + payment_type: match payment_method_type { + Some(pm_type) => PaymentType::try_from(&pm_type)?, + None => PaymentType::Scheme, + }, stored_payment_method_id: Secret::new( connector_mandate_ids.get_connector_mandate_id()?, ),
2024-07-08T14:02:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> remove mandatory payment_method_type check in MIT, as we won't necessarily have this in CIT ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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/5245 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### CIT payment via Adyen without payment_method_type ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_FdbwTgkrJgCahVeugTVGJ3KWbS0UiIADoLlJoMfP2gzxicfOqbJ3HXcjoP8fjr8I' \ --data-raw '{ "amount": 1212, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "adyen_test", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111145551142", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "state": "CA", "first_name": "John", "city": "San Francisco", "zip": "44545", "country": "US", "line1": "52 Julianastraat", "line2": "52 Julianastraat", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone 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": "128.0.0.1" }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" }, { "product_name": "Apple iphone 15", "quantity": 1, "amount": -100, "account_name": "transaction_processing" } ] }' ``` ### Recurring Payment MIT ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_FdbwTgkrJgCahVeugTVGJ3KWbS0UiIADoLlJoMfP2gzxicfOqbJ3HXcjoP8fjr8I' \ --data-raw '{ "amount": 1212, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "scheme_test1", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "billing": { "address": { "state": "CA", "first_name": "John", "city": "San Francisco", "zip": "44545", "country": "US", "line1": "52 Julianastraat", "line2": "52 Julianastraat", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "off_session": true, "recurring_details": { "type":"payment_method_id", "data":"pm_7uWrqPlgdejkhaczULUY" }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" }, { "product_name": "Apple iphone 15", "quantity": 1, "amount": -100, "account_name": "transaction_processing" } ] }' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt --all` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2d31d38c1e35be99e9b0297b197bab81fa5f5030
juspay/hyperswitch
juspay__hyperswitch-5229
Bug: Pass the shipping email whenever the billing details are included in the session token response Currently we pass the below fields if the respective fields are enabled in the business profile if `collect_shipping_details_from_wallet_connector = true` ``` "shipping_address_required": true, "email_required": true, "shipping_address_parameters": { "phone_number_required": true } ``` if `collect_billing_details_from_wallet_connector = true` ``` "billing_address_required": true, "billing_address_parameters": { "phone_number_required": true, "format": "FULL" } ``` This in case we need to pass ` "email_required": true,` if either of fields are true
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index b52cf98b287..664038454a4 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -334,6 +334,21 @@ async fn create_applepay_session_token( }) .flatten(); + // If collect_shipping_details_from_wallet_connector is false, we check if + // collect_billing_details_from_wallet_connector is true. If it is, then we pass the Email and Phone in + // ApplePayShippingContactFields as it is a required parameter and ApplePayBillingContactFields + // does not contain Email and Phone. + let required_shipping_contact_fields_updated = if required_billing_contact_fields.is_some() + && required_shipping_contact_fields.is_none() + { + Some(payment_types::ApplePayShippingContactFields(vec![ + payment_types::ApplePayAddressParameters::Phone, + payment_types::ApplePayAddressParameters::Email, + ])) + } else { + required_shipping_contact_fields + }; + // Get apple pay payment request let applepay_payment_request = get_apple_pay_payment_request( amount_info, @@ -342,7 +357,7 @@ async fn create_applepay_session_token( apple_pay_merchant_identifier.as_str(), merchant_business_country, required_billing_contact_fields, - required_shipping_contact_fields, + required_shipping_contact_fields_updated, )?; let apple_pay_session_response = match ( @@ -670,7 +685,11 @@ fn create_gpay_session_token( delayed_session_token: false, secrets: None, shipping_address_required: required_shipping_contact_fields, - email_required: required_shipping_contact_fields, + // We pass Email as a required field irrespective of + // collect_billing_details_from_wallet_connector or + // collect_shipping_details_from_wallet_connector as it is common to both. + email_required: required_shipping_contact_fields + || is_billing_details_required, shipping_address_parameters: api_models::payments::GpayShippingAddressParameters { phone_number_required: required_shipping_contact_fields,
2024-07-05T14:04:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently we pass the below fields if the respective fields are enabled in the business profile if `collect_shipping_details_from_wallet_connector = true` ``` "shipping_address_required": true, "email_required": true, "shipping_address_parameters": { "phone_number_required": true } ``` if `collect_billing_details_from_wallet_connector = true` ``` "billing_address_required": true, "billing_address_parameters": { "phone_number_required": true, "format": "FULL" } ``` This in case we need to pass ` "email_required": true,` if either of fields are true ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a mca with apple pay and google pay enabled -> Hit the below curl for the business profile ``` curl --location 'http://localhost:8080/account/merchant_1720188909/business_profile/pro_GXFptNIQjSYqmFij5MpV' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false }' ``` -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_XkOoiQAOGF1WZr5hWWxw2yZeZRKLjsFeve4elfwJAIHEgQrPTeP7qr8DW2aMiMrx' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "aaa" }' ``` -> Make a session call with the payment id and there should not be any shipping or billing fields for google pay (for gpay it will be false) or apple pay ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_5b909460522a43a588f9b8728f0982b9' \ --data '{ "payment_id": "pay_L5o2s0kwCaRt8nsMcMk5", "wallets": [], "client_secret": "pay_L5o2s0kwCaRt8nsMcMk5_secret_SVQqKQWw5vYxyBhSuJHZ" }' ``` <img width="1180" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4935adc0-2b05-468e-ac94-4b350daa61e5"> -> Now set the billing fields to true ``` curl --location 'http://localhost:8080/account/merchant_1720188909/business_profile/pro_GXFptNIQjSYqmFij5MpV' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": true }' ``` -> Create a payment with confirm false -> Make a session call. It will have `phone` for apple pay shipping and `"email_required": true,` for goole pay <img width="1172" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/7c9f3eb3-e50d-40ef-9ed6-890ca9a28ebc"> <img width="1202" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9e375da2-054c-48be-af70-2e6bda589653"> -> Now enable both the fields in the business profile ``` curl --location 'http://localhost:8080/account/merchant_1720188909/business_profile/pro_GXFptNIQjSYqmFij5MpV' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": true }' ``` -> Make payment create and session call <img width="1182" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0d8bdb69-009f-411c-b095-2e15854dfbe5"> -> Now enable only shipping ``` curl --location 'http://localhost:8080/account/merchant_1720188909/business_profile/pro_GXFptNIQjSYqmFij5MpV' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_shipping_details_from_wallet_connector": true, "collect_billing_details_from_wallet_connector": false }' ``` <img width="1179" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/826bffce-18c0-4662-8aee-39aec487ccea"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
648cecb204571eb5ac7378d9a217bf74c32a8377
juspay/hyperswitch
juspay__hyperswitch-5235
Bug: Docs: Adding More descriptive details in the Payouts module We have received feedback about the Payout Module in API ref lacking in description of the various fields.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a466288b416..37f696e90f3 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3668,6 +3668,7 @@ pub struct PaymentsResponse { /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] + #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index 9509df8c591..c3ae760215b 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -21,8 +21,7 @@ pub enum PayoutRequest { #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { - /// Unique identifier for the payout. This ensures idempotency for multiple payouts - /// that have been done by a single merchant. This field is auto generated and is returned in the API response. + /// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.** #[schema( value_type = Option<String>, min_length = 30, @@ -31,8 +30,7 @@ pub struct PayoutCreateRequest { )] pub payout_id: Option<String>, // TODO: #1321 https://github.com/juspay/hyperswitch/issues/1321 - /// This is an identifier for the merchant account. This is inferred from the API key - /// provided during the request + /// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.** #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")] pub merchant_id: Option<id_type::MerchantId>, @@ -52,15 +50,15 @@ pub struct PayoutCreateRequest { }))] pub routing: Option<serde_json::Value>, - /// This allows the merchant to manually select a connector with which the payout can go through + /// This field allows the merchant to manually select a connector with which the payout can go through. #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, - /// The boolean value to create payout with connector + /// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it. #[schema(value_type = bool, example = true, default = false)] pub confirm: Option<bool>, - /// The payout_type of the payout request can be specified here + /// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed. #[schema(value_type = PayoutType, example = "card")] pub payout_type: Option<api_enums::PayoutType>, @@ -129,7 +127,7 @@ pub struct PayoutCreateRequest { #[schema(example = "It's my first payout request", value_type = String)] pub description: Option<String>, - /// Type of entity to whom the payout is being carried out to + /// Type of entity to whom the payout is being carried out to, select from the given list of options #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: Option<api_enums::PayoutEntityType>, @@ -141,23 +139,22 @@ pub struct PayoutCreateRequest { #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, - /// Provide a reference to a stored payout method + /// Provide a reference to a stored payout method, used to process the payout. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payout_token: Option<String>, - /// The business profile to use for this payout, if not passed the default business profile - /// associated with the merchant account will be used. + /// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used. pub profile_id: Option<String>, - /// The send method for processing payouts + /// The send method which will be required for processing payouts, check options for better understanding. #[schema(value_type = PayoutSendPriority, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, - /// Whether to get the payout link (if applicable) + /// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_. #[schema(default = false, example = true)] pub payout_link: Option<bool>, - /// custom payout link config for the particular payout + /// Custom payout link config for the particular payout, if payout link is to be generated. #[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)] pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>, @@ -167,6 +164,7 @@ pub struct PayoutCreateRequest { pub session_expiry: Option<u32>, } +/// Custom payout link config for the particular payout, if payout link is to be generated. #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct PayoutCreatePayoutLinkConfig { /// The unique identifier for the collect link. @@ -182,6 +180,7 @@ pub struct PayoutCreatePayoutLinkConfig { pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } +/// The payout method information required for carrying out a payout #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { @@ -486,7 +485,7 @@ pub struct PayoutCreateResponse { #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PayoutAttemptResponse>>, - // If payout link is request, this represents response on + /// If payout link was requested, this contains the link's ID and the URL to render the payout widget #[schema(value_type = Option<PayoutLinkResponse>)] pub payout_link: Option<PayoutLinkResponse>, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 3454a6ba020..e70cc20f266 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2291,6 +2291,7 @@ pub enum PayoutStatus { RequiresVendorAccountCreation, } +/// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, @@ -2317,6 +2318,7 @@ pub enum PayoutType { Wallet, } +/// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, @@ -2350,6 +2352,7 @@ pub enum PayoutEntityType { Personal, } +/// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 02b49f52730..83d005dd637 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -690,7 +690,7 @@ mod amount_conversion_tests { Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] -/// Charge object for refunds +/// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details. pub struct ChargeRefunds { /// Identifier for charge created for the payment pub charge_id: String,
2024-07-07T22:17:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 #5235 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2d235a64e9ab66d9fcd75ed121a2401d891b2268
juspay/hyperswitch
juspay__hyperswitch-5240
Bug: [FEATURE] Add security restrictions on the payout links ### Feature Description Payout links are public to the internet, anybody can make the GET request to fetch the link's HTML response. This renders the link on the client's browser without any sort of validations. Due to the sensitive nature of payout operations, a few restrictions are to be added for security purposes. - Make sure the link is only accessible within iframes (no document loading) - Make sure iframe can only be embedded by hosts in `allowed_domains` (set by consumers, prior to creating payout links) ### Possible Implementation For implementing this, a combination of request and response headers can be consumed. - Incoming request validations - `Sec-Fetch-Dest` header specifies where this link was requested from (for iframes, this should be `iframe` [[ref](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Dest)]) - `Origin/Referer` header specifies the host where the request originated from (this host should be a part of `allowed_domains`) - Client side restrictions - CSP directives can be used for restricting iframes to be accessible only by allowed domains - `frame-ancestors` defines a list of allowed domains which can embed the content inside an iframe - `X-Frame-Options` header is used for the same thing, but for older browsers ### 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! _Note_ - relates to this #4940
diff --git a/Cargo.lock b/Cargo.lock index b29894b49c3..0188b3d6f1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6129,6 +6129,7 @@ dependencies = [ "events", "external_services", "futures 0.3.30", + "globset", "hex", "http 0.2.12", "hyper 0.14.28", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 27bd098953c..b22e0286395 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; #[cfg(feature = "v2")] use common_utils::new_type; @@ -1390,11 +1390,39 @@ pub struct BusinessGenericLinkConfig { /// Custom domain name to be used for hosting the link pub domain_name: Option<String>, + /// A list of allowed domains (glob patterns) where this link can be embedded / opened from + pub allowed_domains: HashSet<String>, + #[serde(flatten)] #[schema(value_type = GenericLinkUiConfig)] pub ui_config: link_utils::GenericLinkUiConfig, } +impl BusinessGenericLinkConfig { + pub fn validate(&self) -> Result<(), &str> { + // Validate host domain name + let host_domain_valid = self + .domain_name + .clone() + .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) + .unwrap_or(true); + if !host_domain_valid { + return Err("Invalid host domain name received"); + } + + let are_allowed_domains_valid = self + .allowed_domains + .clone() + .iter() + .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)); + if !are_allowed_domains_valid { + return Err("Invalid allowed domain names received"); + } + + Ok(()) + } +} + #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct BusinessPaymentLinkConfig { /// Custom domain name to be used for hosting the link in your own domain diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index a9229c74024..848189cd899 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -99,5 +99,21 @@ pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64; /// Minimum allowed length for MerchantReferenceId pub const MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 1; +/// Regex for matching a domain +/// Eg - +/// http://www.example.com +/// https://www.example.com +/// www.example.com +/// example.io +pub const STRICT_DOMAIN_REGEX: &str = r"^(https?://)?(([A-Za-z0-9][-A-Za-z0-9]\.)*[A-Za-z0-9][-A-Za-z0-9]*|(\d{1,3}\.){3}\d{1,3})+(:[0-9]{2,4})?$"; + +/// Regex for matching a wildcard domain +/// Eg - +/// *.example.com +/// *.subdomain.domain.com +/// *://example.com +/// *example.com +pub const WILDCARD_DOMAIN_REGEX: &str = r"^((\*|https?)?://)?((\*\.|[A-Za-z0-9][-A-Za-z0-9]*\.)*[A-Za-z0-9][-A-Za-z0-9]*|((\d{1,3}|\*)\.){3}(\d{1,3}|\*)|\*)(:\*|:[0-9]{2,4})?(/\*)?$"; + /// Maximum allowed length for MerchantName pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64; diff --git a/crates/common_utils/src/link_utils.rs b/crates/common_utils/src/link_utils.rs index 2960209dfc9..e95832eeba9 100644 --- a/crates/common_utils/src/link_utils.rs +++ b/crates/common_utils/src/link_utils.rs @@ -1,4 +1,4 @@ -//! Common +//! This module has common utilities for links in HyperSwitch use std::{collections::HashSet, primitive::i64}; @@ -13,10 +13,13 @@ use diesel::{ }; use error_stack::{report, ResultExt}; use masking::Secret; +use regex::Regex; +#[cfg(feature = "logs")] +use router_env::logger; use serde::Serialize; use utoipa::ToSchema; -use crate::{errors::ParsingError, id_type, types::MinorUnit}; +use crate::{consts, errors::ParsingError, id_type, types::MinorUnit}; #[derive( Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema, @@ -162,6 +165,8 @@ pub struct PayoutLinkData { pub amount: MinorUnit, /// Payout currency pub currency: enums::Currency, + /// A list of allowed domains (glob patterns) where this link can be embedded / opened from + pub allowed_domains: HashSet<String>, } crate::impl_to_sql_from_sql_json!(PayoutLinkData); @@ -209,3 +214,140 @@ pub struct EnabledPaymentMethod { #[schema(value_type = HashSet<PaymentMethodType>)] pub payment_method_types: HashSet<enums::PaymentMethodType>, } + +/// Util function for validating a domain without any wildcard characters. +pub fn validate_strict_domain(domain: &str) -> bool { + Regex::new(consts::STRICT_DOMAIN_REGEX) + .map(|regex| regex.is_match(domain)) + .map_err(|err| { + let err_msg = format!("Invalid strict domain regex: {err:?}"); + #[cfg(feature = "logs")] + logger::error!(err_msg); + err_msg + }) + .unwrap_or(false) +} + +/// Util function for validating a domain with "*" wildcard characters. +pub fn validate_wildcard_domain(domain: &str) -> bool { + Regex::new(consts::WILDCARD_DOMAIN_REGEX) + .map(|regex| regex.is_match(domain)) + .map_err(|err| { + let err_msg = format!("Invalid strict domain regex: {err:?}"); + #[cfg(feature = "logs")] + logger::error!(err_msg); + err_msg + }) + .unwrap_or(false) +} + +#[cfg(test)] +mod domain_tests { + use regex::Regex; + + use super::*; + + #[test] + fn test_validate_strict_domain_regex() { + assert!( + Regex::new(consts::STRICT_DOMAIN_REGEX).is_ok(), + "Strict domain regex is invalid" + ); + } + + #[test] + fn test_validate_wildcard_domain_regex() { + assert!( + Regex::new(consts::WILDCARD_DOMAIN_REGEX).is_ok(), + "Wildcard domain regex is invalid" + ); + } + + #[test] + fn test_validate_strict_domain() { + let valid_domains = vec![ + "example.com", + "example.subdomain.com", + "https://example.com:8080", + "http://example.com", + "example.com:8080", + "example.com:443", + "localhost:443", + "127.0.0.1:443", + ]; + + for domain in valid_domains { + assert!( + validate_strict_domain(domain), + "Could not validate strict domain: {}", + domain + ); + } + + let invalid_domains = vec![ + "", + "invalid.domain.", + "not_a_domain", + "http://example.com/path?query=1#fragment", + "127.0.0.1.2:443", + ]; + + for domain in invalid_domains { + assert!( + !validate_strict_domain(domain), + "Could not validate invalid strict domain: {}", + domain + ); + } + } + + #[test] + fn test_validate_wildcard_domain() { + let valid_domains = vec![ + "example.com", + "example.subdomain.com", + "https://example.com:8080", + "http://example.com", + "example.com:8080", + "example.com:443", + "localhost:443", + "127.0.0.1:443", + "*.com", + "example.*.com", + "example.com:*", + "*:443", + "localhost:*", + "127.0.0.*:*", + "*:*", + ]; + + for domain in valid_domains { + assert!( + validate_wildcard_domain(domain), + "Could not validate wildcard domain: {}", + domain + ); + } + + let invalid_domains = vec![ + "", + "invalid.domain.", + "not_a_domain", + "http://example.com/path?query=1#fragment", + "*.", + ".*", + "example.com:*:", + "*:443:", + ":localhost:*", + "127.00.*:*", + ]; + + for domain in invalid_domains { + assert!( + !validate_wildcard_domain(domain), + "Could not validate invalid wildcard domain: {}", + domain + ); + } + } +} diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs index bb768d21dd0..07d9337e450 100644 --- a/crates/hyperswitch_domain_models/src/api.rs +++ b/crates/hyperswitch_domain_models/src/api.rs @@ -1,4 +1,4 @@ -use std::fmt::Display; +use std::{collections::HashSet, fmt::Display}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, @@ -59,7 +59,13 @@ pub struct PaymentLinkStatusData { } #[derive(Debug, Eq, PartialEq)] -pub enum GenericLinks { +pub struct GenericLinks { + pub allowed_domains: HashSet<String>, + pub data: GenericLinksData, +} + +#[derive(Debug, Eq, PartialEq)] +pub enum GenericLinksData { ExpiredLink(GenericExpiredLinkData), PaymentMethodCollect(GenericLinkFormData), PayoutLink(GenericLinkFormData), @@ -67,12 +73,12 @@ pub enum GenericLinks { PaymentMethodCollectStatus(GenericLinkStatusData), } -impl Display for GenericLinks { +impl Display for GenericLinksData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", - match self { + match *self { Self::ExpiredLink(_) => "ExpiredLink", Self::PaymentMethodCollect(_) => "PaymentMethodCollect", Self::PayoutLink(_) => "PayoutLink", diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index 782376519c2..e660850a983 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -271,6 +271,8 @@ pub enum ApiErrorResponse { InvalidCookie, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_28", message = "{message}")] + LinkConfigurationError { message: String }, #[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}", ignore = "status_code")] IntegrityCheckFailed { reason: String, @@ -615,6 +617,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::ExtendedCardInfoNotFound => { AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None)) } + Self::LinkConfigurationError { message } => { + AER::BadRequest(ApiError::new("IR", 28, message, None)) + }, Self::IntegrityCheckFailed { reason, field_names, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 108b035ec0f..1212869600b 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -58,6 +58,7 @@ dyn-clone = "1.0.17" encoding_rs = "0.8.33" error-stack = "0.4.1" futures = "0.3.30" +globset = "0.4.14" hex = "0.4.3" http = "0.2.12" hyper = "0.14.28" diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index f72b71570a0..e0a9b6c8f87 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -264,6 +264,8 @@ pub enum StripeErrorCode { PaymentMethodDeleteFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")] + LinkConfigurationError { message: String }, #[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, @@ -656,6 +658,9 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { Self::InvalidWalletToken { wallet_name } } errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound, + errors::ApiErrorResponse::LinkConfigurationError { message } => { + Self::LinkConfigurationError { message } + } errors::ApiErrorResponse::IntegrityCheckFailed { reason, field_names, @@ -742,7 +747,8 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::InvalidConnectorConfiguration { .. } | Self::CurrencyConversionFailed | Self::PaymentMethodDeleteFailed - | Self::ExtendedCardInfoNotFound => StatusCode::BAD_REQUEST, + | Self::ExtendedCardInfoNotFound + | Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed | Self::PaymentLinkNotFound diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index 7c1bd7e6712..9ed03c6d2ce 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -141,10 +141,11 @@ where } Ok(api::ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => { - let link_type = (boxed_generic_link_data).to_string(); - match services::generic_link_response::build_generic_link_html(*boxed_generic_link_data) - { - Ok(rendered_html) => api::http_response_html_data(rendered_html), + let link_type = (boxed_generic_link_data).data.to_string(); + match services::generic_link_response::build_generic_link_html( + boxed_generic_link_data.data, + ) { + Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => { api::http_response_err(format!("Error while rendering {} HTML page", link_type)) } @@ -155,7 +156,7 @@ where match *boxed_payment_link_data { api::PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match api::build_payment_link_html(payment_link_data) { - Ok(rendered_html) => api::http_response_html_data(rendered_html), + Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => api::http_response_err( r#"{ "error": { @@ -167,7 +168,7 @@ where } api::PaymentLinkAction::PaymentLinkStatus(payment_link_data) => { match api::get_payment_link_status(payment_link_data) { - Ok(rendered_html) => api::http_response_html_data(rendered_html), + Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => api::http_response_err( r#"{ "error": { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index d8eb1400660..af6d469fd3a 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2061,6 +2061,21 @@ pub async fn update_business_profile( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; + let payout_link_config = request + .payout_link_config + .as_ref() + .map(|payout_conf| match payout_conf.config.validate() { + Ok(_) => payout_conf.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "payout_link_config", + }, + ), + Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { + message: e.to_string() + })), + }) + .transpose()?; + let business_profile_update = storage::business_profile::BusinessProfileUpdate::Update { profile_name: request.profile_name, modified_at: Some(date_time::now()), @@ -2089,14 +2104,7 @@ pub async fn update_business_profile( .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "authentication_connector_details", })?, - payout_link_config: request - .payout_link_config - .as_ref() - .map(Encode::encode_to_value) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "payout_link_config", - })?, + payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing: request.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: request diff --git a/crates/router/src/core/generic_link/payout_link/initiate/script.js b/crates/router/src/core/generic_link/payout_link/initiate/script.js index a8050e90d6e..731f3f76d0a 100644 --- a/crates/router/src/core/generic_link/payout_link/initiate/script.js +++ b/crates/router/src/core/generic_link/payout_link/initiate/script.js @@ -1,153 +1,171 @@ // @ts-check -var widgets = null; -var payoutWidget = null; -// @ts-ignore -var publishableKey = window.__PAYOUT_DETAILS.publishable_key; -var hyper = null; +// Top level checks +var isFramed = false; +try { + isFramed = window.parent.location !== window.location; -/** - * Use - format date in "hh:mm AM/PM timezone MM DD, YYYY" - * @param {Date} date - **/ -function formatDate(date) { - var months = [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", - ]; + // If parent's window object is restricted, DOMException is + // thrown which concludes that the webpage is iframed +} catch (err) { + isFramed = true; +} - var hours = date.getHours(); - var minutes = date.getMinutes(); - // @ts-ignore - minutes = minutes < 10 ? "0" + minutes : minutes; - var suffix = hours > 11 ? "PM" : "AM"; - hours = hours % 12; - hours = hours ? hours : 12; - var day = date.getDate(); - var month = months[date.getMonth()]; - var year = date.getUTCFullYear(); +// Remove the script from DOM incase it's not iframed +if (!isFramed) { + function initializePayoutSDK() { + var errMsg = "You are not allowed to view this content."; + var contentElement = document.getElementById("payout-link"); + if (contentElement instanceof HTMLDivElement) { + contentElement.innerHTML = errMsg; + } else { + document.body.innerHTML = errMsg; + } + } - // @ts-ignore - var locale = navigator.language || navigator.userLanguage; - var timezoneShorthand = date - .toLocaleDateString(locale, { - day: "2-digit", - timeZoneName: "long", - }) - .substring(4) - .split(" ") - .reduce(function (tz, c) { - return tz + c.charAt(0).toUpperCase(); - }, ""); + // webpage is iframed, good to load +} else { + var hyper = null; + var payoutWidget = null; + var widgets = null; + /** + * Use - format date in "hh:mm AM/PM timezone MM DD, YYYY" + * @param {Date} date + **/ + function formatDate(date) { + var months = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ]; - var formatted = - hours + - ":" + - minutes + - " " + - suffix + - " " + - timezoneShorthand + - " " + - month + - " " + - day + - ", " + - year; - return formatted; -} + var hours = date.getHours(); + var minutes = date.getMinutes(); + // @ts-ignore + minutes = minutes < 10 ? "0" + minutes : minutes; + var suffix = hours > 11 ? "PM" : "AM"; + hours = hours % 12; + hours = hours ? hours : 12; + var day = date.getDate(); + var month = months[date.getMonth()]; + var year = date.getUTCFullYear(); -/** - * Trigger - init - * Uses - * - Initialize SDK - * - Update document's icon - */ -function boot() { - // Initialize SDK - // @ts-ignore - if (window.Hyper) { - initializePayoutSDK(); + // @ts-ignore + var locale = navigator.language || navigator.userLanguage; + var timezoneShorthand = date + .toLocaleDateString(locale, { + day: "2-digit", + timeZoneName: "long", + }) + .substring(4) + .split(" ") + .reduce(function (tz, c) { + return tz + c.charAt(0).toUpperCase(); + }, ""); + + var formatted = + hours + + ":" + + minutes + + " " + + suffix + + " " + + timezoneShorthand + + " " + + month + + " " + + day + + ", " + + year; + return formatted; } - // @ts-ignore - var payoutDetails = window.__PAYOUT_DETAILS; + /** + * Trigger - init + * Uses + * - Initialize SDK + * - Update document's icon + */ + function boot() { + // Initialize SDK + // @ts-ignore + if (window.Hyper) { + initializePayoutSDK(); + } + + // @ts-ignore + var payoutDetails = window.__PAYOUT_DETAILS; - // Attach document icon - if (payoutDetails.logo) { - var link = document.createElement("link"); - link.rel = "icon"; - link.href = payoutDetails.logo; - link.type = "image/x-icon"; - document.head.appendChild(link); + // Attach document icon + if (payoutDetails.logo) { + var link = document.createElement("link"); + link.rel = "icon"; + link.href = payoutDetails.logo; + link.type = "image/x-icon"; + document.head.appendChild(link); + } } -} -boot(); + boot(); -/** - * Trigger - post downloading SDK - * Uses - * - Initialize SDK - * - Create a payout widget - * - Mount it in DOM - **/ -function initializePayoutSDK() { - // @ts-ignore - var payoutDetails = window.__PAYOUT_DETAILS; - var clientSecret = payoutDetails.client_secret; - var appearance = { - variables: { - colorPrimary: payoutDetails?.theme?.primary_color || "rgb(0, 109, 249)", - fontFamily: "Work Sans, sans-serif", - fontSizeBase: "16px", - colorText: "rgb(51, 65, 85)", - colorTextSecondary: "#334155B3", - colorPrimaryText: "rgb(51, 65, 85)", - colorTextPlaceholder: "#33415550", - borderColor: "#33415550", - colorBackground: "rgb(255, 255, 255)", - }, - }; - // Instantiate - // @ts-ignore - hyper = window.Hyper(publishableKey, { - isPreloadEnabled: false, - }); - widgets = hyper.widgets({ - appearance: appearance, - clientSecret: clientSecret, - }); + /** + * Trigger - post downloading SDK + * Uses + * - Initialize SDK + * - Create a payout widget + * - Mount it in DOM + **/ + function initializePayoutSDK() { + // @ts-ignore + var payoutDetails = window.__PAYOUT_DETAILS; + var clientSecret = payoutDetails.client_secret; + var publishableKey = payoutDetails.publishable_key; + var appearance = { + variables: { + colorPrimary: payoutDetails?.theme?.primary_color || "rgb(0, 109, 249)", + fontFamily: "Work Sans, sans-serif", + fontSizeBase: "16px", + colorText: "rgb(51, 65, 85)", + }, + }; + // @ts-ignore + hyper = window.Hyper(publishableKey, { + isPreloadEnabled: false, + }); + widgets = hyper.widgets({ + appearance: appearance, + clientSecret: clientSecret, + }); - // Create payment method collect widget - let sessionExpiry = formatDate(new Date(payoutDetails.session_expiry)); - var payoutOptions = { - linkId: payoutDetails.payout_link_id, - payoutId: payoutDetails.payout_id, - customerId: payoutDetails.customer_id, - theme: payoutDetails.theme, - collectorName: payoutDetails.merchant_name, - logo: payoutDetails.logo, - enabledPaymentMethods: payoutDetails.enabled_payment_methods, - returnUrl: payoutDetails.return_url, - sessionExpiry, - amount: payoutDetails.amount, - currency: payoutDetails.currency, - flow: "PayoutLinkInitiate", - }; - payoutWidget = widgets.create("paymentMethodCollect", payoutOptions); + // Create payment method collect widget + let sessionExpiry = formatDate(new Date(payoutDetails.session_expiry)); + var payoutOptions = { + linkId: payoutDetails.payout_link_id, + payoutId: payoutDetails.payout_id, + customerId: payoutDetails.customer_id, + theme: payoutDetails.theme, + collectorName: payoutDetails.merchant_name, + logo: payoutDetails.logo, + enabledPaymentMethods: payoutDetails.enabled_payment_methods, + returnUrl: payoutDetails.return_url, + sessionExpiry, + amount: payoutDetails.amount, + currency: payoutDetails.currency, + flow: "PayoutLinkInitiate", + }; + payoutWidget = widgets.create("paymentMethodCollect", payoutOptions); - // Mount - if (payoutWidget !== null) { - payoutWidget.mount("#payout-link"); + // Mount + if (payoutWidget !== null) { + payoutWidget.mount("#payout-link"); + } } } diff --git a/crates/router/src/core/generic_link/payout_link/status/styles.css b/crates/router/src/core/generic_link/payout_link/status/styles.css index cf2d89b6a30..d5668553129 100644 --- a/crates/router/src/core/generic_link/payout_link/status/styles.css +++ b/crates/router/src/core/generic_link/payout_link/status/styles.css @@ -78,9 +78,9 @@ body { } #resource-info-container { - width: calc(100% - 80px); + width: 100%; border-top: 1px solid rgb(231, 234, 241); - padding: 20px 40px; + padding: 20px 0; } #resource-info { display: flex; @@ -88,7 +88,7 @@ body { } #info-key { text-align: right; - font-size: 15px; + font-size: 14px; min-width: 10ch; } #info-val { @@ -101,13 +101,33 @@ body { margin-top: 40px; } -@media only screen and (max-width: 1199px) { +@media only screen and (max-width: 420px) { body { overflow-y: scroll; } + body { + justify-content: start; + } + .main { - width: auto; + width: 100%; min-width: 300px; } + + #status-card { + box-shadow: none; + } + + #info-key { + min-width: 12ch; + } + + #info-val { + font-size: 11px; + } + + #resource-info { + margin: 0 10px; + } } diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index a7a87b6d96e..a9a85b8e04e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1,3 +1,4 @@ +use std::collections::HashSet; pub mod cards; pub mod migration; pub mod surcharge_decision_configs; @@ -13,7 +14,10 @@ use diesel_models::{ enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData, }; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; +use hyperswitch_domain_models::{ + api::{GenericLinks, GenericLinksData}, + payments::{payment_attempt::PaymentAttempt, PaymentIntent}, +}; use masking::PeekInterface; use router_env::{instrument, tracing}; use time::Duration; @@ -27,7 +31,7 @@ use crate::{ pm_auth as core_pm_auth, }, routes::{app::StorageInterface, SessionState}, - services::{self, GenericLinks}, + services, types::{ api::{self, payments}, domain, storage, @@ -245,7 +249,10 @@ pub async fn render_pm_collect_link( theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( - GenericLinks::ExpiredLink(expired_link_data), + GenericLinks { + allowed_domains: HashSet::from([]), + data: GenericLinksData::ExpiredLink(expired_link_data), + }, ))) // else, send back form link @@ -303,7 +310,11 @@ pub async fn render_pm_collect_link( html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( - GenericLinks::PaymentMethodCollect(generic_form_data), + GenericLinks { + allowed_domains: HashSet::from([]), + + data: GenericLinksData::PaymentMethodCollect(generic_form_data), + }, ))) } } @@ -344,7 +355,11 @@ pub async fn render_pm_collect_link( css_data: serialized_css_content, }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( - GenericLinks::PaymentMethodCollectStatus(generic_status_data), + GenericLinks { + allowed_domains: HashSet::from([]), + + data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data), + }, ))) } } diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 0d4c525f104..7fca84dbccf 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -1,5 +1,9 @@ -use std::collections::{HashMap, HashSet}; +use std::{ + cmp::Ordering, + collections::{HashMap, HashSet}, +}; +use actix_web::http::header; use api_models::payouts; use common_utils::{ ext_traits::{Encode, OptionExt}, @@ -8,14 +12,15 @@ use common_utils::{ }; use diesel_models::PayoutLinkUpdate; use error_stack::ResultExt; +use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use super::errors::{RouterResponse, StorageErrorExt}; use crate::{ configs::settings::{PaymentMethodFilterKey, PaymentMethodFilters}, - core::payments::helpers, + core::{payments::helpers, payouts::validator}, errors, routes::{app::StorageInterface, SessionState}, - services::{self, GenericLinks}, + services, types::domain, }; @@ -24,6 +29,7 @@ pub async fn initiate_payout_link( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutLinkInitiateRequest, + request_headers: &header::HeaderMap, ) -> RouterResponse<services::GenericLinkFormData> { let db: &dyn StorageInterface = &*state.store; let merchant_id = &merchant_account.merchant_id; @@ -59,6 +65,8 @@ pub async fn initiate_payout_link( message: "payout link not found".to_string(), })?; + validator::validate_payout_link_render_request(request_headers, &payout_link)?; + // Check status and return form data accordingly let has_expired = common_utils::date_time::now() > payout_link.expiry; let status = payout_link.link_status.clone(); @@ -97,7 +105,10 @@ pub async fn initiate_payout_link( } Ok(services::ApplicationResponse::GenericLinkForm(Box::new( - GenericLinks::ExpiredLink(expired_link_data), + GenericLinks { + allowed_domains: (link_data.allowed_domains), + data: GenericLinksData::ExpiredLink(expired_link_data), + }, ))) } @@ -146,9 +157,17 @@ pub async fn initiate_payout_link( }; // Fetch enabled payout methods from the request. If not found, fetch the enabled payout methods from MCA, // If none are configured for merchant connector accounts, fetch them from the default enabled payout methods. - let enabled_payment_methods = link_data + let mut enabled_payment_methods = link_data .enabled_payment_methods .unwrap_or(fallback_enabled_payout_methods.to_vec()); + + // Sort payment methods (cards first) + enabled_payment_methods.sort_by(|a, b| match (a.payment_method, b.payment_method) { + (_, common_enums::PaymentMethod::Card) => Ordering::Greater, + (common_enums::PaymentMethod::Card, _) => Ordering::Less, + _ => Ordering::Equal, + }); + let js_data = payouts::PayoutLinkDetails { publishable_key: masking::Secret::new(merchant_account.publishable_key), client_secret: link_data.client_secret.clone(), @@ -186,7 +205,10 @@ pub async fn initiate_payout_link( html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( - GenericLinks::PayoutLink(generic_form_data), + GenericLinks { + allowed_domains: (link_data.allowed_domains), + data: GenericLinksData::PayoutLink(generic_form_data), + }, ))) } @@ -225,7 +247,10 @@ pub async fn initiate_payout_link( css_data: serialized_css_content, }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( - GenericLinks::PayoutLinkStatus(generic_status_data), + GenericLinks { + allowed_domains: (link_data.allowed_domains), + data: GenericLinksData::PayoutLinkStatus(generic_status_data), + }, ))) } } diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 848d57bce87..e36036eb798 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -5,38 +5,41 @@ pub mod retry; pub mod validator; use std::vec::IntoIter; -use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse}; +use api_models::{self, admin, enums as api_enums, payouts::PayoutLinkResponse}; use common_utils::{ consts, crypto::Encryptable, ext_traits::{AsyncExt, ValueExt}, - link_utils::PayoutLinkStatus, + id_type::CustomerId, + link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus}, pii, types::MinorUnit, }; -use diesel_models::{enums as storage_enums, generic_link::PayoutLink}; +use diesel_models::{ + enums as storage_enums, + generic_link::{GenericLinkNew, PayoutLink}, +}; use error_stack::{report, ResultExt}; #[cfg(feature = "olap")] use futures::future::join_all; #[cfg(feature = "olap")] use hyperswitch_domain_models::errors::StorageError; -use masking::PeekInterface; +use masking::{PeekInterface, Secret}; #[cfg(feature = "payout_retry")] use retry::GsmValidation; use router_env::{instrument, logger, tracing}; use scheduler::utils as pt_utils; use serde_json; +use time::Duration; -use super::{ - errors::{ConnectorErrorExt, StorageErrorExt}, - payments::customers, -}; #[cfg(feature = "olap")] use crate::types::domain::behaviour::Conversion; use crate::{ core::{ - errors::{self, CustomResult, RouterResponse, RouterResult}, - payments::{self, helpers as payment_helpers}, + errors::{ + self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt, + }, + payments::{self, customers, helpers as payment_helpers}, utils as core_utils, }, db::StorageInterface, @@ -1106,7 +1109,7 @@ pub async fn create_recipient( add_external_account_addition_task( &*state.store, payout_data, - common_utils::date_time::now().saturating_add(time::Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)), + common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2172,7 +2175,7 @@ pub async fn payout_create_db_entries( let payout_link = match req.payout_link { Some(true) => Some( - validator::create_payout_link( + create_payout_link( state, &business_profile, &customer_id, @@ -2479,3 +2482,139 @@ async fn validate_and_get_business_profile( }) } } + +#[allow(clippy::too_many_arguments)] +pub async fn create_payout_link( + state: &SessionState, + business_profile: &storage::BusinessProfile, + customer_id: &CustomerId, + merchant_id: &String, + req: &payouts::PayoutCreateRequest, + payout_id: &String, +) -> RouterResult<PayoutLink> { + let payout_link_config_req = req.payout_link_config.to_owned(); + + // Fetch all configs + let default_config = &state.conf.generic_link.payout_link; + let profile_config = business_profile + .payout_link_config + .as_ref() + .map(|config| { + config + .clone() + .parse_value::<admin::BusinessPayoutLinkConfig>("BusinessPayoutLinkConfig") + }) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "payout_link_config in business_profile", + })?; + let profile_ui_config = profile_config.as_ref().map(|c| c.config.ui_config.clone()); + let ui_config = payout_link_config_req + .as_ref() + .and_then(|config| config.ui_config.clone()) + .or(profile_ui_config); + + // Validate allowed_domains presence + let allowed_domains = profile_config + .as_ref() + .map(|config| config.config.allowed_domains.to_owned()) + .get_required_value("allowed_domains") + .change_context(errors::ApiErrorResponse::LinkConfigurationError { + message: "Payout links cannot be used without setting allowed_domains in profile" + .to_string(), + })?; + + // Form data to be injected in the link + let (logo, merchant_name, theme) = match ui_config { + Some(config) => (config.logo, config.merchant_name, config.theme), + _ => (None, None, None), + }; + let payout_link_config = GenericLinkUiConfig { + logo, + merchant_name, + theme, + }; + let client_secret = utils::generate_id(consts::ID_LENGTH, "payout_link_secret"); + let base_url = profile_config + .as_ref() + .and_then(|c| c.config.domain_name.as_ref()) + .map(|domain| format!("https://{}", domain)) + .unwrap_or(state.base_url.clone()); + let session_expiry = req + .session_expiry + .as_ref() + .map_or(default_config.expiry, |expiry| *expiry); + let url = format!("{base_url}/payout_link/{merchant_id}/{payout_id}"); + let link = url::Url::parse(&url) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| format!("Failed to form payout link URL - {}", url))?; + let req_enabled_payment_methods = payout_link_config_req + .as_ref() + .and_then(|req| req.enabled_payment_methods.to_owned()); + let amount = req + .amount + .as_ref() + .get_required_value("amount") + .attach_printable("amount is a required value when creating payout links")?; + let currency = req + .currency + .as_ref() + .get_required_value("currency") + .attach_printable("currency is a required value when creating payout links")?; + let payout_link_id = core_utils::get_or_generate_id( + "payout_link_id", + &payout_link_config_req + .as_ref() + .and_then(|config| config.payout_link_id.clone()), + "payout_link", + )?; + + let data = PayoutLinkData { + payout_link_id: payout_link_id.clone(), + customer_id: customer_id.clone(), + payout_id: payout_id.to_string(), + link, + client_secret: Secret::new(client_secret), + session_expiry, + ui_config: payout_link_config, + enabled_payment_methods: req_enabled_payment_methods, + amount: MinorUnit::from(*amount), + currency: *currency, + allowed_domains, + }; + + create_payout_link_db_entry(state, merchant_id, &data, req.return_url.clone()).await +} + +pub async fn create_payout_link_db_entry( + state: &SessionState, + merchant_id: &String, + payout_link_data: &PayoutLinkData, + return_url: Option<String>, +) -> RouterResult<PayoutLink> { + let db: &dyn StorageInterface = &*state.store; + + let link_data = serde_json::to_value(payout_link_data) + .map_err(|_| report!(errors::ApiErrorResponse::InternalServerError)) + .attach_printable("Failed to convert PayoutLinkData to Value")?; + + let payout_link = GenericLinkNew { + link_id: payout_link_data.payout_link_id.to_string(), + primary_reference: payout_link_data.payout_id.to_string(), + merchant_id: merchant_id.to_string(), + link_type: common_enums::GenericLinkType::PayoutLink, + link_status: GenericLinkStatus::PayoutLink(PayoutLinkStatus::Initiated), + link_data, + url: payout_link_data.link.to_string().into(), + return_url, + expiry: common_utils::date_time::now() + + Duration::seconds(payout_link_data.session_expiry.into()), + ..Default::default() + }; + + db.insert_payout_link(payout_link) + .await + .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { + message: "payout link already exists".to_string(), + }) +} diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs index 3e69216167d..a1332181f6d 100644 --- a/crates/router/src/core/payouts/validator.rs +++ b/crates/router/src/core/payouts/validator.rs @@ -1,33 +1,25 @@ -use api_models::admin; +use std::collections::HashSet; + +use actix_web::http::header; #[cfg(feature = "olap")] use common_utils::errors::CustomResult; -use common_utils::{ - ext_traits::ValueExt, - id_type::CustomerId, - link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus}, - types::MinorUnit, -}; -use diesel_models::{ - business_profile::BusinessProfile, - generic_link::{GenericLinkNew, PayoutLink}, -}; +use diesel_models::generic_link::PayoutLink; use error_stack::{report, ResultExt}; +use globset::Glob; pub use hyperswitch_domain_models::errors::StorageError; -use masking::Secret; -use router_env::{instrument, tracing}; -use time::Duration; +use router_env::{instrument, logger, tracing}; +use url::Url; use super::helpers; use crate::{ - consts, core::{ - errors::{self, RouterResult, StorageErrorExt}, + errors::{self, RouterResult}, utils as core_utils, }, db::StorageInterface, routes::SessionState, types::{api::payouts, domain, storage}, - utils::{self, OptionExt}, + utils, }; #[instrument(skip(db))] @@ -192,128 +184,97 @@ pub(super) fn validate_payout_list_request_for_joins( Ok(()) } -#[allow(clippy::too_many_arguments)] -pub async fn create_payout_link( - state: &SessionState, - business_profile: &BusinessProfile, - customer_id: &CustomerId, - merchant_id: &String, - req: &payouts::PayoutCreateRequest, - payout_id: &String, -) -> RouterResult<PayoutLink> { - let payout_link_config_req = req.payout_link_config.to_owned(); - // Create payment method collect link ID - let payout_link_id = core_utils::get_or_generate_id( - "payout_link_id", - &payout_link_config_req - .as_ref() - .and_then(|config| config.payout_link_id.clone()), - "payout_link", - )?; - - // Fetch all configs - let default_config = &state.conf.generic_link.payout_link; - let profile_config = business_profile - .payout_link_config - .as_ref() - .map(|config| { - config - .clone() - .parse_value::<admin::BusinessPayoutLinkConfig>("BusinessPayoutLinkConfig") - }) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "payout_link_config in business_profile", - })?; - let profile_ui_config = profile_config.as_ref().map(|c| c.config.ui_config.clone()); - let ui_config = payout_link_config_req - .as_ref() - .and_then(|config| config.ui_config.clone()) - .or(profile_ui_config); - - // Form data to be injected in the link - let (logo, merchant_name, theme) = match ui_config { - Some(config) => (config.logo, config.merchant_name, config.theme), - _ => (None, None, None), - }; - let payout_link_config = GenericLinkUiConfig { - logo, - merchant_name, - theme, - }; - let client_secret = utils::generate_id(consts::ID_LENGTH, "payout_link_secret"); - let base_url = profile_config - .as_ref() - .and_then(|c| c.config.domain_name.as_ref()) - .map(|domain| format!("https://{}", domain)) - .unwrap_or(state.base_url.clone()); - let session_expiry = req - .session_expiry - .as_ref() - .map_or(default_config.expiry, |expiry| *expiry); - let url = format!("{base_url}/payout_link/{merchant_id}/{payout_id}"); - let link = url::Url::parse(&url) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| format!("Failed to form payout link URL - {}", url))?; - let req_enabled_payment_methods = payout_link_config_req - .as_ref() - .and_then(|req| req.enabled_payment_methods.to_owned()); - let amount = req - .amount - .as_ref() - .get_required_value("amount") - .attach_printable("amount is a required value when creating payout links")?; - let currency = req - .currency - .as_ref() - .get_required_value("currency") - .attach_printable("currency is a required value when creating payout links")?; - - let data = PayoutLinkData { - payout_link_id: payout_link_id.clone(), - customer_id: customer_id.clone(), - payout_id: payout_id.to_string(), - link, - client_secret: Secret::new(client_secret), - session_expiry, - ui_config: payout_link_config, - enabled_payment_methods: req_enabled_payment_methods, - amount: MinorUnit::from(*amount), - currency: *currency, - }; +pub fn validate_payout_link_render_request( + request_headers: &header::HeaderMap, + payout_link: &PayoutLink, +) -> RouterResult<()> { + let link_id = payout_link.link_id.to_owned(); + let link_data = payout_link.link_data.to_owned(); - create_payout_link_db_entry(state, merchant_id, &data, req.return_url.clone()).await -} + // Fetch destination is "iframe" + match request_headers.get("sec-fetch-dest").and_then(|v| v.to_str().ok()) { + Some("iframe") => Ok(()), + Some(requestor) => Err(report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payout_link".to_string(), + })) + .attach_printable_lazy(|| { + format!( + "Access to payout_link [{}] is forbidden when requested through {}", + link_id, requestor + ) + }), + None => Err(report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payout_link".to_string(), + })) + .attach_printable_lazy(|| { + format!( + "Access to payout_link [{}] is forbidden when sec-fetch-dest is not present in request headers", + link_id + ) + }), + }?; -pub async fn create_payout_link_db_entry( - state: &SessionState, - merchant_id: &String, - payout_link_data: &PayoutLinkData, - return_url: Option<String>, -) -> RouterResult<PayoutLink> { - let db: &dyn StorageInterface = &*state.store; + // Validate origin / referer + let domain_in_req = { + let origin_or_referer = request_headers + .get("origin") + .or_else(|| request_headers.get("referer")) + .and_then(|v| v.to_str().ok()) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payout_link".to_string(), + }) + }) + .attach_printable_lazy(|| { + format!( + "Access to payout_link [{}] is forbidden when origin or referer is not present in request headers", + link_id + ) + })?; - let link_data = serde_json::to_value(payout_link_data) - .map_err(|_| report!(errors::ApiErrorResponse::InternalServerError)) - .attach_printable("Failed to convert PayoutLinkData to Value")?; + let url = Url::parse(origin_or_referer) + .map_err(|_| { + report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payout_link".to_string(), + }) + }) + .attach_printable_lazy(|| { + format!("Invalid URL found in request headers {}", origin_or_referer) + })?; - let payout_link = GenericLinkNew { - link_id: payout_link_data.payout_link_id.to_string(), - primary_reference: payout_link_data.payout_id.to_string(), - merchant_id: merchant_id.to_string(), - link_type: common_enums::GenericLinkType::PayoutLink, - link_status: GenericLinkStatus::PayoutLink(PayoutLinkStatus::Initiated), - link_data, - url: payout_link_data.link.to_string().into(), - return_url, - expiry: common_utils::date_time::now() - + Duration::seconds(payout_link_data.session_expiry.into()), - ..Default::default() + url.host_str() + .and_then(|host| url.port().map(|port| format!("{}:{}", host, port))) + .or_else(|| url.host_str().map(String::from)) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payout_link".to_string(), + }) + }) + .attach_printable_lazy(|| { + format!("host or port not found in request headers {:?}", url) + })? }; - db.insert_payout_link(payout_link) - .await - .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { - message: "payout link already exists".to_string(), + if is_domain_allowed(&domain_in_req, link_data.allowed_domains) { + Ok(()) + } else { + Err(report!(errors::ApiErrorResponse::AccessForbidden { + resource: "payout_link".to_string(), + })) + .attach_printable_lazy(|| { + format!( + "Access to payout_link [{}] is forbidden from requestor - {}", + link_id, domain_in_req + ) }) + } +} + +fn is_domain_allowed(domain: &str, allowed_domains: HashSet<String>) -> bool { + allowed_domains.iter().any(|allowed_domain| { + Glob::new(allowed_domain) + .map(|glob| glob.compile_matcher().is_match(domain)) + .map_err(|err| logger::error!("Invalid glob pattern! - {:?}", err)) + .unwrap_or(false) + }) } diff --git a/crates/router/src/routes/payout_link.rs b/crates/router/src/routes/payout_link.rs index 34850bdea6e..e3a0327c329 100644 --- a/crates/router/src/routes/payout_link.rs +++ b/crates/router/src/routes/payout_link.rs @@ -23,13 +23,14 @@ pub async fn render_payout_link( merchant_id: merchant_id.clone(), payout_id, }; + let headers = req.headers(); Box::pin(api::server_wrap( flow, state, &req, payload.clone(), |state, auth, req, _| { - initiate_payout_link(state, auth.merchant_account, auth.key_store, req) + initiate_payout_link(state, auth.merchant_account, auth.key_store, req, headers) }, &auth::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 5456d4c2502..5dc46d35652 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -13,8 +13,9 @@ use std::{ use actix_http::header::HeaderMap; use actix_web::{ - body, http::header::HeaderValue, web, FromRequest, HttpRequest, HttpResponse, Responder, - ResponseError, + body, + http::header::{HeaderName, HeaderValue}, + web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError, }; use api_models::enums::{CaptureMethod, PaymentMethodType}; pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient}; @@ -1049,9 +1050,18 @@ where } Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => { - let link_type = (boxed_generic_link_data).to_string(); - match build_generic_link_html(*boxed_generic_link_data) { - Ok(rendered_html) => http_response_html_data(rendered_html), + let link_type = boxed_generic_link_data.data.to_string(); + match build_generic_link_html(boxed_generic_link_data.data) { + Ok(rendered_html) => { + let domains_str = boxed_generic_link_data + .allowed_domains + .into_iter() + .collect::<Vec<String>>() + .join(" "); + let csp_header = format!("frame-ancestors 'self' {};", domains_str); + let headers = HashSet::from([("content-security-policy", csp_header)]); + http_response_html_data(rendered_html, Some(headers)) + } Err(_) => { http_response_err(format!("Error while rendering {} HTML page", link_type)) } @@ -1062,7 +1072,7 @@ where match *boxed_payment_link_data { PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match build_payment_link_html(payment_link_data) { - Ok(rendered_html) => http_response_html_data(rendered_html), + Ok(rendered_html) => http_response_html_data(rendered_html, None), Err(_) => http_response_err( r#"{ "error": { @@ -1074,7 +1084,7 @@ where } PaymentLinkAction::PaymentLinkStatus(payment_link_data) => { match get_payment_link_status(payment_link_data) { - Ok(rendered_html) => http_response_html_data(rendered_html), + Ok(rendered_html) => http_response_html_data(rendered_html, None), Err(_) => http_response_err( r#"{ "error": { @@ -1231,8 +1241,22 @@ pub fn http_response_file_data<T: body::MessageBody + 'static>( HttpResponse::Ok().content_type(content_type).body(res) } -pub fn http_response_html_data<T: body::MessageBody + 'static>(res: T) -> HttpResponse { - HttpResponse::Ok().content_type(mime::TEXT_HTML).body(res) +pub fn http_response_html_data<T: body::MessageBody + 'static>( + res: T, + optional_headers: Option<HashSet<(&'static str, String)>>, +) -> HttpResponse { + let mut res_builder = HttpResponse::Ok(); + res_builder.content_type(mime::TEXT_HTML); + + if let Some(headers) = optional_headers { + for (key, value) in headers { + if let Ok(header_val) = HeaderValue::try_from(value) { + res_builder.insert_header((HeaderName::from_static(key), header_val)); + } + } + } + + res_builder.body(res) } pub fn http_response_ok() -> HttpResponse { diff --git a/crates/router/src/services/api/generic_link_response.rs b/crates/router/src/services/api/generic_link_response.rs index fb8b3b3ec74..497926481ab 100644 --- a/crates/router/src/services/api/generic_link_response.rs +++ b/crates/router/src/services/api/generic_link_response.rs @@ -1,25 +1,27 @@ use common_utils::errors::CustomResult; use error_stack::ResultExt; +use hyperswitch_domain_models::api::{ + GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinksData, +}; use tera::{Context, Tera}; -use super::{GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinks}; use crate::core::errors; pub fn build_generic_link_html( - boxed_generic_link_data: GenericLinks, + boxed_generic_link_data: GenericLinksData, ) -> CustomResult<String, errors::ApiErrorResponse> { match boxed_generic_link_data { - GenericLinks::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data), + GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data), - GenericLinks::PaymentMethodCollect(pm_collect_data) => { + GenericLinksData::PaymentMethodCollect(pm_collect_data) => { build_pm_collect_link_html(&pm_collect_data) } - GenericLinks::PaymentMethodCollectStatus(pm_collect_data) => { + GenericLinksData::PaymentMethodCollectStatus(pm_collect_data) => { build_pm_collect_link_status_html(&pm_collect_data) } - GenericLinks::PayoutLink(payout_link_data) => build_payout_link_html(&payout_link_data), + GenericLinksData::PayoutLink(payout_link_data) => build_payout_link_html(&payout_link_data), - GenericLinks::PayoutLinkStatus(pm_collect_data) => { + GenericLinksData::PayoutLinkStatus(pm_collect_data) => { build_payout_link_status_html(&pm_collect_data) } } diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 55288e02f86..884e47c6fc4 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -9,7 +9,7 @@ pub use api_models::admin::{ ToggleKVResponse, WebhookDetails, }; use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; -use error_stack::ResultExt; +use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{merchant_key_store::MerchantKeyStore, type_encryption::decrypt}; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -194,6 +194,21 @@ pub async fn create_business_profile( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; + let payout_link_config = request + .payout_link_config + .as_ref() + .map(|payout_conf| match payout_conf.config.validate() { + Ok(_) => payout_conf.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "payout_link_config", + }, + ), + Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { + message: e.to_string() + })), + }) + .transpose()?; + Ok(storage::business_profile::BusinessProfileNew { profile_id, merchant_id: merchant_account.merchant_id, @@ -246,14 +261,7 @@ pub async fn create_business_profile( .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "authentication_connector_details", })?, - payout_link_config: request - .payout_link_config - .as_ref() - .map(Encode::encode_to_value) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "payout_link_config", - })?, + payout_link_config, is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, diff --git a/migrations/2024-07-17-064610_add_allowed_domains_to_link_data/down.sql b/migrations/2024-07-17-064610_add_allowed_domains_to_link_data/down.sql new file mode 100644 index 00000000000..623bec2a2f0 --- /dev/null +++ b/migrations/2024-07-17-064610_add_allowed_domains_to_link_data/down.sql @@ -0,0 +1,3 @@ +UPDATE generic_link +SET link_data = link_data - 'allowed_domains' +WHERE link_data -> 'allowed_domains' = '["*"]'::jsonb AND link_type = 'payout_link'; \ No newline at end of file diff --git a/migrations/2024-07-17-064610_add_allowed_domains_to_link_data/up.sql b/migrations/2024-07-17-064610_add_allowed_domains_to_link_data/up.sql new file mode 100644 index 00000000000..affa2755d7e --- /dev/null +++ b/migrations/2024-07-17-064610_add_allowed_domains_to_link_data/up.sql @@ -0,0 +1,5 @@ +UPDATE generic_link +SET link_data = jsonb_set(link_data, '{allowed_domains}', '["*"]'::jsonb) +WHERE + NOT link_data ? 'allowed_domains' + AND link_type = 'payout_link'; \ No newline at end of file
2024-07-05T11:32:36Z
## Type of Change - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR includes below changes - - adding `allowed_domains` field in payout link config - this is added at both business profile level and individual payout txns - business profile config is used as a fallback in case `allowed_domains` are not passed in payout link's create request - this is a required field in production env - server side validations for incoming render request - check `Sec-Fetch-Dest` [[ref](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Dest)] for request source (must be `iframe`) - check `Origin / Referer` for the host of the incoming request (must match one in `allowed_domains`) - these are skipped if `allowed_domains` is not setup (only in non-production env) - client side headers - attach CSP header - `frame-ancestors` for directing which hosts can embed the links in an iframe [[ref](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors)] - ~~attach X-Frame header - similar to CSP, but for older browsers [[ref](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options)]~~ _Removing this as it's outdated_ - update status UI for payout links feat(generic_link): add allowed_domains in GenericLink response feat(payout_link): add allowed_domains in payout_link_config (fallback profile config + payout request config) feat(payout_link): consume meta headers for validating render request for payout links feat(payout_link): consume CSP and X-Frame headers in the link's response ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? **Tested locally using postman** 1. Update business profile's `payout_link_config` to include `allowed_domains` ``` curl --location 'http://localhost:8080/account/merchant_1721206540/business_profile/pro_iMeDAsjCBueHxdjCiZ9I' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "payout_link_config": { "allowed_domains": ["127.0.0.1:5500"] } }' ``` 2. Create a payout link ``` curl --location 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Ew5ejag6iXMc80CDUUflU4daqTvm0wsMc1AgUo174U7iaV1GFvf8kkwt8LLCxDkT' \ --data '{ "amount": 3000, "currency": "EUR", "billing": { "address": { "city": "Hoogeveen", "country": "NL", "line1": "Raadhuisplein", "line2": "92", "zip": "7901 BW", "state": "FL" }, "phone": { "number": "0650242319", "country_code": "+31" } }, "payout_link": true, "payout_link_config": { "theme": "#143F1E", "logo": "https://upload.wikimedia.org/wikipedia/commons/8/84/Spotify_icon.svg", "merchant_name": "Spotify" } }' ``` 3. Try opening this link in a new tab (should not open) 4. Open this inside an iframe (should open provided the `allowed_domains` and the iframe's host is same) **Test cases** ``` cargo test --package common_utils --lib -- link_utils::domain_tests --show-output ``` ![image](https://github.com/user-attachments/assets/cdc03c39-f914-4a5a-9166-ceb83f8b92ec) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
ecc862c3543be37e2cc7959f450ca51770978ae5
juspay/hyperswitch
juspay__hyperswitch-5221
Bug: feat(events): add payment feature metadata & customer email to the payment intent events Add a hashed value of these fields and use them to provide global search
diff --git a/Cargo.lock b/Cargo.lock index d0b9894970b..d40d7e2ee05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1577,6 +1577,7 @@ dependencies = [ "cc", "cfg-if 1.0.0", "constant_time_eq 0.3.0", + "serde", ] [[package]] @@ -1958,6 +1959,7 @@ name = "common_utils" version = "0.1.0" dependencies = [ "async-trait", + "blake3", "bytes 1.6.0", "common_enums", "diesel", diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 7d32e76928b..67f32396b74 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -82,6 +82,7 @@ audit_events_topic = "topic" # Kafka topic to be used for Payment payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events authentication_analytics_topic = "topic" # Kafka topic to be used for Authentication events +fraud_check_analytics_topic = "topic" # Kafka topic to be used for Fraud Check events # File storage configuration [file_storage] diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index 1237db061bd..269864bf44a 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -51,7 +51,18 @@ pub async fn msearch_results( if let Some(customer_email) = filters.customer_email { if !customer_email.is_empty() { query_builder - .add_filter_clause("customer_email.keyword".to_string(), customer_email.clone()) + .add_filter_clause( + "customer_email.keyword".to_string(), + customer_email + .iter() + .filter_map(|email| { + // TODO: Add trait based inputs instead of converting this to strings + serde_json::to_value(email) + .ok() + .and_then(|a| a.as_str().map(|a| a.to_string())) + }) + .collect(), + ) .switch()?; } }; @@ -147,7 +158,18 @@ pub async fn search_results( if let Some(customer_email) = filters.customer_email { if !customer_email.is_empty() { query_builder - .add_filter_clause("customer_email.keyword".to_string(), customer_email.clone()) + .add_filter_clause( + "customer_email.keyword".to_string(), + customer_email + .iter() + .filter_map(|email| { + // TODO: Add trait based inputs instead of converting this to strings + serde_json::to_value(email) + .ok() + .and_then(|a| a.as_str().map(|a| a.to_string())) + }) + .collect(), + ) .switch()?; } }; diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index b2af4f6759c..034a2a94356 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -1,3 +1,4 @@ +use common_utils::hashing::HashedString; use serde_json::Value; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] @@ -5,7 +6,7 @@ pub struct SearchFilters { pub payment_method: Option<Vec<String>>, pub currency: Option<Vec<String>>, pub status: Option<Vec<String>>, - pub customer_email: Option<Vec<String>>, + pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index c0b9ce756f7..311686f27de 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4821,8 +4821,11 @@ pub struct PaymentsStartRequest { #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios - #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, + // TODO: Convert this to hashedstrings to avoid PII sensitive data + /// Additional tags to be used for global search + #[schema(value_type = Option<RedirectResponse>)] + pub search_tags: Option<Vec<Secret<String>>>, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 58cdf447fd4..568dc00a970 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -44,6 +44,8 @@ tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"], optional url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } uuid = { version = "1.8.0", features = ["v7"] } +blake3 = { version = "1.5.1", features = ["serde"] } + # First party crates rusty-money = { git = "https://github.com/varunsrin/rusty_money", rev = "bbc0150742a0fff905225ff11ee09388e9babdcc", features = ["iso", "crypto"] } diff --git a/crates/common_utils/src/hashing.rs b/crates/common_utils/src/hashing.rs new file mode 100644 index 00000000000..d08cd9f0868 --- /dev/null +++ b/crates/common_utils/src/hashing.rs @@ -0,0 +1,22 @@ +use masking::{PeekInterface, Secret, Strategy}; +use serde::{Deserialize, Serialize, Serializer}; + +#[derive(Clone, Debug, Deserialize)] +/// Represents a hashed string using blake3's hashing strategy. +pub struct HashedString<T: Strategy<String>>(Secret<String, T>); + +impl<T: Strategy<String>> Serialize for HashedString<T> { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let hashed_value = blake3::hash(self.0.peek().as_bytes()).to_hex(); + hashed_value.serialize(serializer) + } +} + +impl<T: Strategy<String>> From<Secret<String, T>> for HashedString<T> { + fn from(value: Secret<String, T>) -> Self { + Self(value) + } +} diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 8e305dd3d67..d1449f2a7d2 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -31,6 +31,8 @@ pub mod static_cache; pub mod types; pub mod validation; +/// Used for hashing +pub mod hashing; #[cfg(feature = "metrics")] pub mod metrics; diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index 2921b237177..9d4b96200ba 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -14,6 +14,7 @@ use error_stack::ResultExt; use masking::{ExposeInterface, Secret, Strategy, WithType}; #[cfg(feature = "logs")] use router_env::logger; +use serde::Deserialize; use crate::{ crypto::Encryptable, @@ -205,7 +206,7 @@ where } /// Strategy for masking Email -#[derive(Debug)] +#[derive(Debug, Copy, Clone, Deserialize)] pub enum EmailStrategy {} impl<T> Strategy<T> for EmailStrategy diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 4af5a2ed308..18e62b9c1c8 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -944,6 +944,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { param: req.param.map(Secret::new), json_payload: Some(req.json_payload.unwrap_or(serde_json::json!({})).into()), }), + search_tags: None, }), ..Default::default() }; @@ -1230,6 +1231,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { req.json_payload.unwrap_or(serde_json::json!({})).into(), ), }), + search_tags: None, }), ..Default::default() }; diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index 0a4ac6d6c2c..0dd11087896 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -1,7 +1,8 @@ -use common_utils::{crypto::Encryptable, id_type, types::MinorUnit}; +use common_utils::{crypto::Encryptable, hashing::HashedString, id_type, pii, types::MinorUnit}; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payments::PaymentIntent; -use masking::Secret; +use masking::{PeekInterface, Secret}; +use serde_json::Value; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] @@ -32,7 +33,10 @@ pub struct KafkaPaymentIntent<'a> { pub business_label: Option<&'a String>, pub attempt_count: i16, pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>, + pub customer_email: Option<HashedString<pii::EmailStrategy>>, + pub feature_metadata: Option<&'a Value>, + pub merchant_order_reference_id: Option<&'a String>, + pub billing_details: Option<Encryptable<Secret<Value>>>, } impl<'a> KafkaPaymentIntent<'a> { @@ -61,7 +65,16 @@ impl<'a> KafkaPaymentIntent<'a> { business_label: intent.business_label.as_ref(), attempt_count: intent.attempt_count, payment_confirm_source: intent.payment_confirm_source, - billing_details: intent.billing_details.clone(), + customer_email: intent + .customer_details + .as_ref() + .and_then(|value| value.get_inner().peek().as_object()) + .and_then(|obj| obj.get("email")) + .and_then(|email| email.as_str()) + .map(|email| HashedString::from(Secret::new(email.to_string()))), + feature_metadata: intent.feature_metadata.as_ref(), + merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), + billing_details: None, } } } diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index b8ffb659457..1824ad71c7d 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -1,7 +1,8 @@ -use common_utils::{crypto::Encryptable, id_type, types::MinorUnit}; +use common_utils::{crypto::Encryptable, hashing::HashedString, id_type, pii, types::MinorUnit}; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payments::PaymentIntent; -use masking::Secret; +use masking::{PeekInterface, Secret}; +use serde_json::Value; use time::OffsetDateTime; #[serde_with::skip_serializing_none] @@ -33,7 +34,10 @@ pub struct KafkaPaymentIntentEvent<'a> { pub business_label: Option<&'a String>, pub attempt_count: i16, pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>, + pub customer_email: Option<HashedString<pii::EmailStrategy>>, + pub feature_metadata: Option<&'a Value>, + pub merchant_order_reference_id: Option<&'a String>, + pub billing_details: Option<Encryptable<Secret<Value>>>, } impl<'a> KafkaPaymentIntentEvent<'a> { @@ -62,7 +66,16 @@ impl<'a> KafkaPaymentIntentEvent<'a> { business_label: intent.business_label.as_ref(), attempt_count: intent.attempt_count, payment_confirm_source: intent.payment_confirm_source, - billing_details: intent.billing_details.clone(), + customer_email: intent + .customer_details + .as_ref() + .and_then(|value| value.get_inner().peek().as_object()) + .and_then(|obj| obj.get("email")) + .and_then(|email| email.as_str()) + .map(|email| HashedString::from(Secret::new(email.to_string()))), + feature_metadata: intent.feature_metadata.as_ref(), + merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), + billing_details: None, } } }
2024-07-05T11:47:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Implemented hashing of `customer_email` using `blake3::hash`, and added this to PaymentIntent kafka events - Enabled search using `customer_email` filter in dashboard globalsearch as well - Added `feature_metadata` with `search_tags` for dashboard globalsearch ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Hashing of customer_email helps in masking of data to help protect privacy ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested it using Postman curls: - Made a payment with the `customer_email` and `search_tags` in `feature_metadata` set ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_IG9ateOUhGE0KLFEItNN1tsJXcr5M62N7zlbtOlUtStTfPpzSomswbQa4aO2k1B4' \ --data-raw '{ "amount": 6540, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "test@hyperswitch.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_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" }, "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", "feature_metadata": { "search_tags": ["dubai", "tokyo"] }, "metadata": { "data2": "camel", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Hit the `analytics/v1/search` with the following curl: ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGU2ZWVhYzEtMWVjNi00ZWQyLWJhY2YtMDUzOTFiZGE3YjI1IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzE5OTA0MzA1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMDI3MTg0NSwib3JnX2lkIjoib3JnX0c4Zk85a09UTXl1OHBXUEVQSUcwIn0.2Pdjr1w82ImWbccLcAthHzJ8LU959xSHRZ5PrJCFtoE' \ --header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data-raw '{ "query": "merchant_1719904305", "filters": { "currency": [ "INR" ], "customer_email": [ "test@hyperswitch.com" ] } }' ``` You should be able to get the results in the `payment_intents` index ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
16e8f4b263842bcf0767ed06ee94d73e02247dd8
juspay/hyperswitch
juspay__hyperswitch-5217
Bug: fix(bug): drainer fails to deserialize refund status it seems due to recent changes that the refund status is encoded in snakecase whereas the older drainer working on PascalCase is failing breaking backwards compatibility
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 36cc0bcb11c..87b436ca922 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1574,11 +1574,16 @@ pub enum PaymentType { #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { + #[serde(alias = "Failure")] Failure, + #[serde(alias = "ManualReview")] ManualReview, #[default] + #[serde(alias = "Pending")] Pending, + #[serde(alias = "Success")] Success, + #[serde(alias = "TransactionFailure")] TransactionFailure, }
2024-07-05T08:28:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Add backwards compatibility aliases on refund status ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 drainer relies on the serde json representation to parse these results and hence needs a backwards compatible way to parse older & newer formats. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - make refunds with kv mode and check the operations tab for their presence ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
1904ffad889bbf2c77e959fda60c0c55fd57f596
juspay/hyperswitch
juspay__hyperswitch-5212
Bug: fix(users): make id option in auth select The id the request body of auth select should be option. It is because list will be empty for hyperswitch authentication method.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 66d4986129a..43b476c9f67 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -377,5 +377,5 @@ pub struct AuthIdQueryParam { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthSelectRequest { - pub id: String, + pub id: Option<String>, } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 952b74f5797..49993f3873a 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2306,21 +2306,38 @@ pub async fn terminate_auth_select( .change_context(UserErrors::InternalServerError)? .into(); - let user_authentication_method = state - .store - .get_user_authentication_method_by_id(&req.id) - .await - .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; + if let Some(id) = &req.id { + let user_authentication_method = state + .store + .get_user_authentication_method_by_id(id) + .await + .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; - let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; - let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; + let current_flow = + domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; + let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; - // Skip SSO if continue with password(TOTP) - if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) - && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) - { - next_flow = next_flow.skip(user_from_db, &state).await?; + // Skip SSO if continue with password(TOTP) + if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) + && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) + { + next_flow = next_flow.skip(user_from_db, &state).await?; + } + let token = next_flow.get_token(&state).await?; + + return auth::cookies::set_cookie_response( + user_api::TokenResponse { + token: token.clone(), + token_type: next_flow.get_flow().into(), + }, + token, + ); } + + // Giving totp token for hyperswtich users when no id is present in the request body + let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; + let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; + next_flow = next_flow.skip(user_from_db, &state).await?; let token = next_flow.get_token(&state).await?; auth::cookies::set_cookie_response(
2024-07-04T14:26:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Make id option in auth select. If no id is passed the response should give totp token ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#5212](https://github.com/juspay/hyperswitch/issues/5212) ## How did you test it? request: ``` curl --location 'http://localhost:8080/user/auth/select' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6ImF1dGhfc2VsZWN0Iiwib3JpZ2luIjoiYWNjZXB0X2ludml0YXRpb25fZnJvbV9lbWFpbCIsInBhdGgiOltdLCJleHAiOjE4MTk1ODQ1NDN9._vo2f5SpbKFcpNipvLqbJTsEJ5YwSdL__3Igg7yU4-4' \ --header 'Content-Type: application/json' \ --data '{ } ' ``` Response: ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJhY2NlcHRfaW52aXRhdGlvbl9mcm9tX2VtYWlsIiwicGF0aCI6WyJhdXRoX3NlbGVjdCJdLCJleHAiOjE3MjAyNzYzNzh9.PiMJfzzYsNLyxUyRnBvgwKTmOgAvte1M_wU2ZBSswik", "token_type": "totp" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
cf5c1041b787ecf74519eb5077ebacd3b1beef67
juspay/hyperswitch
juspay__hyperswitch-5237
Bug: [FEAT] add key in keymanager [FEAT] add key in keymanager
diff --git a/config/config.example.toml b/config/config.example.toml index e4a15e7fb12..5a734237513 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -28,6 +28,10 @@ certificate = "/path/to/certificate.pem" idle_pool_connection_timeout = 90 # Timeout for idle pool connections (defaults to 90s) +# Configuration for the Key Manager Service +[key_manager] +url = "http://localhost:5000" # URL of the encryption service + # Main SQL data store credentials [master_database] username = "db_user" # DB Username diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 67f32396b74..3f7fb52f502 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -248,6 +248,10 @@ payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" +# Configuration for the Key Manager Service +[key_manager] +url = "http://localhost:5000" # URL of the encryption service + # This section provides some secret values. [secrets] master_enc_key = "sample_key" # Master Encryption key used to encrypt merchant wise encryption key. Should be 32-byte long. diff --git a/config/development.toml b/config/development.toml index b3548b35d06..23682ab1542 100644 --- a/config/development.toml +++ b/config/development.toml @@ -12,6 +12,9 @@ metrics_enabled = false use_xray_generator = false bg_metrics_collection_interval_in_secs = 15 +[key_manager] +url = "http://localhost:5000" + # TODO: Update database credentials before running application [master_database] username = "db_user" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index b11ca005741..10e5545c1bd 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -90,6 +90,9 @@ default_command_timeout = 30 unresponsive_timeout = 10 max_feed_count = 200 +[key_manager] +url = "http://localhost:5000" + [cors] max_age = 30 # origins = "http://localhost:8080,http://localhost:9000" diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index e9b84285847..ec9172b7fdf 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -994,6 +994,12 @@ pub struct ToggleKVResponse { pub kv_enabled: bool, } +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct TransferKeyResponse { + /// The identifier for the Merchant Account + #[schema(example = 32)] + pub total_transferred: usize, +} #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleKVRequest { #[serde(skip_deserializing)] diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 4dcf1a3896a..3757dd98d78 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -80,6 +80,7 @@ impl_misc_api_event_type!( ToggleKVRequest, ToggleAllKVRequest, ToggleAllKVResponse, + TransferKeyResponse, MerchantAccountDeleteResponse, MerchantAccountUpdate, CardInfoResponse, diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index b357a3389d9..b8c893ae25d 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -20,7 +20,7 @@ use crate::user::{ SsoSignInRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, - VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + UserTransferKeyResponse, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -85,6 +85,7 @@ common_utils::impl_misc_api_event_type!( UpdateUserAuthenticationMethodRequest, GetSsoAuthUrlRequest, SsoSignInRequest, + UserTransferKeyResponse, AuthSelectRequest ); diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 43b476c9f67..7c0b21f9679 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -379,3 +379,8 @@ pub struct AuthIdQueryParam { pub struct AuthSelectRequest { pub id: Option<String>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct UserTransferKeyResponse { + pub total_transferred: usize, +} diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 45953210701..f6c3d8b6d0d 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -8,6 +8,8 @@ readme = "README.md" license.workspace = true [features] +keymanager = ["dep:router_env"] +keymanager_mtls = ["reqwest/rustls-tls"] signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_env", "dep:futures"] async_ext = ["dep:async-trait", "dep:futures"] logs = ["dep:router_env"] diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index d5e86985041..23b4f2be4fe 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -145,6 +145,42 @@ where } } +#[allow(missing_docs)] +#[derive(Debug, thiserror::Error)] +pub enum KeyManagerClientError { + #[error("Failed to construct header from the given value")] + FailedtoConstructHeader, + #[error("Failed to send request to Keymanager")] + RequestNotSent(String), + #[error("URL encoding of request failed")] + UrlEncodingFailed, + #[error("Failed to build the reqwest client ")] + ClientConstructionFailed, + #[error("Failed to send the request to Keymanager")] + RequestSendFailed, + #[error("Internal Server Error Received {0:?}")] + InternalServerError(bytes::Bytes), + #[error("Bad request received {0:?}")] + BadRequest(bytes::Bytes), + #[error("Unexpected Error occurred while calling the KeyManager")] + Unexpected(bytes::Bytes), + #[error("Response Decoding failed")] + ResponseDecodingFailed, +} + +#[allow(missing_docs)] +#[derive(Debug, thiserror::Error)] +pub enum KeyManagerError { + #[error("Failed to add key to the KeyManager")] + KeyAddFailed, + #[error("Failed to transfer the key to the KeyManager")] + KeyTransferFailed, + #[error("Failed to Encrypt the data in the KeyManager")] + EncryptionFailed, + #[error("Failed to Decrypt the data in the KeyManager")] + DecryptionFailed, +} + /// Allow [error_stack::Report] to convert between error types /// This auto-implements [ReportSwitchExt] for the corresponding errors pub trait ErrorSwitch<T> { diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rs new file mode 100644 index 00000000000..ecdb9b63ad5 --- /dev/null +++ b/crates/common_utils/src/keymanager.rs @@ -0,0 +1,175 @@ +//! Consists of all the common functions to use the Keymanager. + +use core::fmt::Debug; +use std::str::FromStr; + +use error_stack::ResultExt; +use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +#[cfg(feature = "keymanager_mtls")] +use masking::PeekInterface; +use once_cell::sync::OnceCell; +use router_env::{instrument, logger, tracing}; + +use crate::{ + errors, + types::keymanager::{ + DataKeyCreateResponse, EncryptionCreateRequest, EncryptionTransferRequest, KeyManagerState, + }, +}; + +const CONTENT_TYPE: &str = "Content-Type"; +static ENCRYPTION_API_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); + +/// Get keymanager client constructed from the url and state +#[instrument(skip_all)] +#[allow(unused_mut)] +fn get_api_encryption_client( + state: &KeyManagerState, +) -> errors::CustomResult<reqwest::Client, errors::KeyManagerClientError> { + let get_client = || { + let mut client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .pool_idle_timeout(std::time::Duration::from_secs( + state.client_idle_timeout.unwrap_or_default(), + )); + + #[cfg(feature = "keymanager_mtls")] + { + let cert = state.cert.clone(); + let ca = state.ca.clone(); + + let identity = reqwest::Identity::from_pem(cert.peek().as_ref()) + .change_context(errors::KeyManagerClientError::ClientConstructionFailed)?; + let ca_cert = reqwest::Certificate::from_pem(ca.peek().as_ref()) + .change_context(errors::KeyManagerClientError::ClientConstructionFailed)?; + + client = client + .use_rustls_tls() + .identity(identity) + .add_root_certificate(ca_cert) + .https_only(true); + } + + client + .build() + .change_context(errors::KeyManagerClientError::ClientConstructionFailed) + }; + + Ok(ENCRYPTION_API_CLIENT.get_or_try_init(get_client)?.clone()) +} + +/// Generic function to send the request to keymanager +#[instrument(skip_all)] +pub async fn send_encryption_request<T>( + state: &KeyManagerState, + headers: HeaderMap, + url: String, + method: Method, + request_body: T, +) -> errors::CustomResult<reqwest::Response, errors::KeyManagerClientError> +where + T: serde::Serialize, +{ + let client = get_api_encryption_client(state)?; + let url = reqwest::Url::parse(&url) + .change_context(errors::KeyManagerClientError::UrlEncodingFailed)?; + + client + .request(method, url) + .json(&request_body) + .headers(headers) + .send() + .await + .change_context(errors::KeyManagerClientError::RequestNotSent( + "Unable to send request to encryption service".to_string(), + )) +} + +/// Generic function to call the Keymanager and parse the response back +#[instrument(skip_all)] +pub async fn call_encryption_service<T, R>( + state: &KeyManagerState, + method: Method, + endpoint: &str, + request_body: T, +) -> errors::CustomResult<R, errors::KeyManagerClientError> +where + T: serde::Serialize + Send + Sync + 'static + Debug, + R: serde::de::DeserializeOwned, +{ + let url = format!("{}/{endpoint}", &state.url); + + logger::info!(key_manager_request=?request_body); + + let response = send_encryption_request( + state, + HeaderMap::from_iter( + vec![( + HeaderName::from_str(CONTENT_TYPE) + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + HeaderValue::from_str("application/json") + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + )] + .into_iter(), + ), + url, + method, + request_body, + ) + .await + .map_err(|err| err.change_context(errors::KeyManagerClientError::RequestSendFailed))?; + + logger::info!(key_manager_response=?response); + + match response.status() { + StatusCode::OK => response + .json::<R>() + .await + .change_context(errors::KeyManagerClientError::ResponseDecodingFailed), + StatusCode::INTERNAL_SERVER_ERROR => { + Err(errors::KeyManagerClientError::InternalServerError( + response + .bytes() + .await + .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, + ) + .into()) + } + StatusCode::BAD_REQUEST => Err(errors::KeyManagerClientError::BadRequest( + response + .bytes() + .await + .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, + ) + .into()), + _ => Err(errors::KeyManagerClientError::Unexpected( + response + .bytes() + .await + .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, + ) + .into()), + } +} + +/// A function to create the key in keymanager +#[instrument(skip_all)] +pub async fn create_key_in_key_manager( + state: &KeyManagerState, + request_body: EncryptionCreateRequest, +) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> { + call_encryption_service(state, Method::POST, "key/create", request_body) + .await + .change_context(errors::KeyManagerError::KeyAddFailed) +} + +/// A function to transfer the key in keymanager +#[instrument(skip_all)] +pub async fn transfer_key_to_key_manager( + state: &KeyManagerState, + request_body: EncryptionTransferRequest, +) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> { + call_encryption_service(state, Method::POST, "key/transfer", request_body) + .await + .change_context(errors::KeyManagerError::KeyTransferFailed) +} diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 39826944a1b..9b339fb956e 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -19,6 +19,8 @@ pub mod events; pub mod ext_traits; pub mod fp_utils; pub mod id_type; +#[cfg(feature = "keymanager")] +pub mod keymanager; pub mod link_utils; pub mod macros; pub mod new_type; diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index f469a0299ff..02b49f52730 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1,4 +1,6 @@ //! Types that can be used in other crates +pub mod keymanager; + use std::{ fmt::Display, ops::{Add, Sub}, diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs new file mode 100644 index 00000000000..356ccdd4832 --- /dev/null +++ b/crates/common_utils/src/types/keymanager.rs @@ -0,0 +1,41 @@ +#![allow(missing_docs)] + +#[cfg(feature = "keymanager_mtls")] +use masking::Secret; +use serde::{Deserialize, Serialize}; + +#[derive(Debug)] +pub struct KeyManagerState { + pub url: String, + pub client_idle_timeout: Option<u64>, + #[cfg(feature = "keymanager_mtls")] + pub ca: Secret<String>, + #[cfg(feature = "keymanager_mtls")] + pub cert: Secret<String>, +} +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +#[serde(tag = "data_identifier", content = "key_identifier")] +pub enum Identifier { + User(String), + Merchant(String), +} + +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +pub struct EncryptionCreateRequest { + #[serde(flatten)] + pub identifier: Identifier, +} + +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +pub struct EncryptionTransferRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub key: String, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct DataKeyCreateResponse { + #[serde(flatten)] + pub identifier: Identifier, + pub key_version: String, +} diff --git a/crates/diesel_models/src/query/merchant_key_store.rs b/crates/diesel_models/src/query/merchant_key_store.rs index 1be82cb2c18..fc4d09c4989 100644 --- a/crates/diesel_models/src/query/merchant_key_store.rs +++ b/crates/diesel_models/src/query/merchant_key_store.rs @@ -54,4 +54,20 @@ impl MerchantKeyStore { ) .await } + + pub async fn list_all_key_stores(conn: &PgPooledConn) -> StorageResult<Vec<Self>> { + generics::generic_filter::< + <Self as HasTable>::Table, + _, + <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, + _, + >( + conn, + dsl::merchant_id.ne_all(vec!["".to_string()]), + None, + None, + None, + ) + .await + } } diff --git a/crates/diesel_models/src/query/user_key_store.rs b/crates/diesel_models/src/query/user_key_store.rs index 42dfe223b1a..5aad28bb562 100644 --- a/crates/diesel_models/src/query/user_key_store.rs +++ b/crates/diesel_models/src/query/user_key_store.rs @@ -14,6 +14,22 @@ impl UserKeyStoreNew { } impl UserKeyStore { + pub async fn get_all_user_key_stores(conn: &PgPooledConn) -> StorageResult<Vec<Self>> { + generics::generic_filter::< + <Self as HasTable>::Table, + _, + <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, + _, + >( + conn, + dsl::user_id.ne_all(vec!["".to_string()]), + None, + None, + None, + ) + .await + } + pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f23029e36d6..4373c7fb169 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -11,10 +11,12 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm", "tls"] tls = ["actix-web/rustls-0_22"] +keymanager_mtls = ["reqwest/rustls-tls","common_utils/keymanager_mtls"] email = ["external_services/email", "scheduler/email", "olap"] +keymanager_create = [] frm = ["api_models/frm", "hyperswitch_domain_models/frm"] stripe = ["dep:serde_qs"] -release = ["stripe", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3"] +release = ["stripe", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3","keymanager_mtls","keymanager_create"] olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] @@ -107,7 +109,7 @@ api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] 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", "metrics"] } +common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics","keymanager"] } 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 } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index bab567899f5..819a5a06cb4 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -8810,3 +8810,15 @@ impl Default for super::settings::ApiKeys { } } } + +impl Default for super::settings::KeyManagerConfig { + fn default() -> Self { + Self { + url: String::from("localhost:5000"), + #[cfg(feature = "keymanager_mtls")] + ca: String::default().into(), + #[cfg(feature = "keymanager_mtls")] + cert: String::default().into(), + } + } +} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 1ab2e519b7a..884feee9124 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -197,6 +197,35 @@ impl SecretsHandler for settings::PaymentMethodAuth { } } +#[async_trait::async_trait] +impl SecretsHandler for settings::KeyManagerConfig { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + _secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + #[cfg(feature = "keymanager_mtls")] + let keyconfig = value.get_inner(); + + #[cfg(feature = "keymanager_mtls")] + let ca = _secret_management_client + .get_secret(keyconfig.ca.clone()) + .await?; + + #[cfg(feature = "keymanager_mtls")] + let cert = _secret_management_client + .get_secret(keyconfig.cert.clone()) + .await?; + + Ok(value.transition_state(|keyconfig| Self { + #[cfg(feature = "keymanager_mtls")] + ca, + #[cfg(feature = "keymanager_mtls")] + cert, + ..keyconfig + })) + } +} + #[async_trait::async_trait] impl SecretsHandler for settings::Secrets { async fn convert_to_raw_secret( @@ -318,6 +347,14 @@ pub(crate) async fn fetch_raw_secrets( .await .expect("Failed to decrypt payment method auth configs"); + #[allow(clippy::expect_used)] + let key_manager = settings::KeyManagerConfig::convert_to_raw_secret( + conf.key_manager, + secret_management_client, + ) + .await + .expect("Failed to decrypt keymanager configs"); + #[allow(clippy::expect_used)] let user_auth_methods = settings::UserAuthMethodSettings::convert_to_raw_secret( conf.user_auth_methods, @@ -337,6 +374,7 @@ pub(crate) async fn fetch_raw_secrets( secrets_management: conf.secrets_management, proxy: conf.proxy, env: conf.env, + key_manager, #[cfg(feature = "olap")] replica_database, secrets, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a29d7e1502d..33024a6e112 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -69,6 +69,7 @@ pub struct Settings<S: SecretState> { pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, pub locker: Locker, + pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, pub forex_api: SecretStateContainer<ForexApi, S>, pub refund: Refund, @@ -213,6 +214,15 @@ pub struct KvConfig { pub soft_kill: Option<bool>, } +#[derive(Debug, Deserialize, Clone)] +pub struct KeyManagerConfig { + pub url: String, + #[cfg(feature = "keymanager_mtls")] + pub cert: Secret<String>, + #[cfg(feature = "keymanager_mtls")] + pub ca: Secret<String>, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct GenericLink { pub payment_method_collect: GenericLinkEnvConfig, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 7402d9730fd..5dc4e295919 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -14,6 +14,7 @@ pub mod connector_onboarding; pub mod currency; pub mod customers; pub mod disputes; +pub mod encryption; pub mod errors; pub mod files; #[cfg(feature = "frm")] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index dc72ec2ba89..67b3a05adb7 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -9,6 +9,8 @@ use common_utils::{ ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, pii, }; +#[cfg(all(feature = "keymanager_create", feature = "olap"))] +use common_utils::{keymanager, types::keymanager as km_types}; use diesel_models::configs; use error_stack::{report, FutureExt, ResultExt}; use futures::future::try_join_all; @@ -22,6 +24,7 @@ use crate::types::transformers::ForeignFrom; use crate::{ consts, core::{ + encryption::transfer_encryption_key, errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payments::helpers, routing::helpers as routing_helpers, @@ -125,6 +128,19 @@ pub async fn create_merchant_account( .create_domain_model_from_request(db, key_store.clone()) .await?; + #[cfg(feature = "keymanager_create")] + { + keymanager::create_key_in_key_manager( + &(&state).into(), + km_types::EncryptionCreateRequest { + identifier: km_types::Identifier::Merchant(merchant_id.clone()), + }, + ) + .await + .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) + .attach_printable("Failed to insert key to KeyManager")?; + } + db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into()) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; @@ -2491,6 +2507,18 @@ pub(crate) fn validate_connector_auth_type( } } +pub async fn transfer_key_store_to_key_manager( + state: SessionState, +) -> RouterResponse<admin_types::TransferKeyResponse> { + let resp = transfer_encryption_key(&state).await?; + + Ok(service_api::ApplicationResponse::Json( + admin_types::TransferKeyResponse { + total_transferred: resp, + }, + )) +} + #[cfg(feature = "dummy_connector")] pub async fn validate_dummy_connector_enabled( state: &SessionState, diff --git a/crates/router/src/core/encryption.rs b/crates/router/src/core/encryption.rs new file mode 100644 index 00000000000..7f7945bfd1c --- /dev/null +++ b/crates/router/src/core/encryption.rs @@ -0,0 +1,55 @@ +use base64::Engine; +use common_utils::{ + keymanager::transfer_key_to_key_manager, + types::keymanager::{EncryptionTransferRequest, Identifier}, +}; +use error_stack::ResultExt; +use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; +use masking::ExposeInterface; + +use crate::{consts::BASE64_ENGINE, errors, types::domain::UserKeyStore, SessionState}; + +pub async fn transfer_encryption_key( + state: &SessionState, +) -> errors::CustomResult<usize, errors::ApiErrorResponse> { + let db = &*state.store; + let key_stores = db + .get_all_key_stores(&db.get_master_key().to_vec().into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + send_request_to_key_service_for_merchant(state, key_stores).await +} + +pub async fn send_request_to_key_service_for_merchant( + state: &SessionState, + keys: Vec<MerchantKeyStore>, +) -> errors::CustomResult<usize, errors::ApiErrorResponse> { + futures::future::try_join_all(keys.into_iter().map(|key| async move { + let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); + let req = EncryptionTransferRequest { + identifier: Identifier::Merchant(key.merchant_id.clone()), + key: key_encoded, + }; + transfer_key_to_key_manager(&state.into(), req).await + })) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(|v| v.len()) +} + +pub async fn send_request_to_key_service_for_user( + state: &SessionState, + keys: Vec<UserKeyStore>, +) -> errors::CustomResult<usize, errors::ApiErrorResponse> { + futures::future::try_join_all(keys.into_iter().map(|key| async move { + let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); + let req = EncryptionTransferRequest { + identifier: Identifier::User(key.user_id.clone()), + key: key_encoded, + }; + transfer_key_to_key_manager(&state.into(), req).await + })) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(|v| v.len()) +} diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 2abcb5ea78b..bbc0336abcf 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -27,6 +27,7 @@ use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; use crate::services::email::types as email_types; use crate::{ consts, + core::encryption::send_request_to_key_service_for_user, db::domain::user_authentication_method::DEFAULT_USER_AUTH_METHOD, routes::{app::ReqState, SessionState}, services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse}, @@ -1911,6 +1912,25 @@ pub async fn generate_recovery_codes( })) } +pub async fn transfer_user_key_store_keymanager( + state: SessionState, +) -> UserResponse<user_api::UserTransferKeyResponse> { + let db = &state.global_store; + + let key_stores = db + .get_all_user_key_store(&state.store.get_master_key().to_vec().into()) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::Json( + user_api::UserTransferKeyResponse { + total_transferred: send_request_to_key_service_for_user(&state, key_stores) + .await + .change_context(UserErrors::InternalServerError)?, + }, + )) +} + pub async fn verify_recovery_code( state: SessionState, user_token: auth::UserIdFromAuth, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index edf8a53346c..ce0821c6322 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2096,6 +2096,12 @@ impl MerchantKeyStoreInterface for KafkaStore { .list_multiple_key_stores(merchant_ids, key) .await } + async fn get_all_key_stores( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { + self.diesel_store.get_all_key_stores(key).await + } } #[async_trait::async_trait] @@ -2958,6 +2964,13 @@ impl UserKeyStoreInterface for KafkaStore { .get_user_key_store_by_user_id(user_id, key) .await } + + async fn get_all_user_key_store( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { + self.diesel_store.get_all_user_key_store(key).await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 77eb2609835..42a862e2d3d 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -40,6 +40,11 @@ pub trait MerchantKeyStoreInterface { merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; + + async fn get_all_key_stores( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; } #[async_trait::async_trait] @@ -163,6 +168,26 @@ impl MerchantKeyStoreInterface for Store { })) .await } + + async fn get_all_key_stores( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + let fetch_func = || async { + diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores(&conn) + .await + .map_err(|err| report!(errors::StorageError::from(err))) + }; + + futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + key_store + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + })) + .await + } } #[async_trait::async_trait] @@ -251,6 +276,21 @@ impl MerchantKeyStoreInterface for MockDb { ) .await } + async fn get_all_key_stores( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { + let merchant_key_stores = self.merchant_key_store.lock().await; + + futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { + merchant_key + .to_owned() + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + })) + .await + } } #[cfg(test)] diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs index e08d17d280e..c7e48037e96 100644 --- a/crates/router/src/db/user_key_store.rs +++ b/crates/router/src/db/user_key_store.rs @@ -27,6 +27,11 @@ pub trait UserKeyStoreInterface { user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; + + async fn get_all_user_key_store( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>; } #[async_trait::async_trait] @@ -65,6 +70,27 @@ impl UserKeyStoreInterface for Store { .await .change_context(errors::StorageError::DecryptionError) } + + async fn get_all_user_key_store( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + + let fetch_func = || async { + diesel_models::user_key_store::UserKeyStore::get_all_user_key_stores(&conn) + .await + .map_err(|err| report!(errors::StorageError::from(err))) + }; + + futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + key_store + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + })) + .await + } } #[async_trait::async_trait] @@ -98,6 +124,22 @@ impl UserKeyStoreInterface for MockDb { .change_context(errors::StorageError::DecryptionError) } + async fn get_all_user_key_store( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { + let user_key_store = self.user_key_store.lock().await; + + futures::future::try_join_all(user_key_store.iter().map(|user_key| async { + user_key + .to_owned() + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + })) + .await + } + #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 3f08834e441..da12c98c77e 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -446,16 +446,16 @@ pub async fn merchant_account_toggle_kv( .await } -/// Merchant Account - Toggle KV +/// Merchant Account - Transfer Keys /// -/// Toggle KV mode for all Merchant Accounts +/// Transfer Merchant Encryption key to keymanager #[instrument(skip_all)] pub async fn merchant_account_toggle_all_kv( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::ToggleAllKVRequest>, ) -> HttpResponse { - let flow = Flow::ConfigKeyUpdate; + let flow = Flow::MerchantTransferKey; let payload = json_payload.into_inner(); api::server_wrap( @@ -651,6 +651,27 @@ pub async fn merchant_account_kv_status( .await } +/// Merchant Account - KV Status +/// +/// Toggle KV mode for the Merchant Account +#[instrument(skip_all)] +pub async fn merchant_account_transfer_keys( + state: web::Data<AppState>, + req: HttpRequest, +) -> HttpResponse { + let flow = Flow::ConfigKeyFetch; + api::server_wrap( + flow, + state, + &req, + (), + |state, _, _, _| transfer_key_store_to_key_manager(state), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::ToggleExtendedCardInfo))] pub async fn toggle_extended_card_info( state: web::Data<AppState>, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 797de75dfcf..d82f98f295d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1028,6 +1028,9 @@ impl MerchantAccount { .route(web::post().to(merchant_account_toggle_kv)) .route(web::get().to(merchant_account_kv_status)), ) + .service( + web::resource("/transfer").route(web::post().to(merchant_account_transfer_keys)), + ) .service(web::resource("/kv").route(web::post().to(merchant_account_toggle_all_kv))) .service( web::resource("/{id}") @@ -1398,6 +1401,11 @@ impl User { .route(web::post().to(set_dashboard_metadata)), ); + route = route.service( + web::scope("/key") + .service(web::resource("/transfer").route(web::post().to(transfer_user_key))), + ); + // Two factor auth routes route = route.service( web::scope("/2fa") diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 56e8751a979..8f0c1aa804c 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -45,6 +45,7 @@ impl From<Flow> for ApiIdentifier { | Flow::MerchantsAccountRetrieve | Flow::MerchantsAccountUpdate | Flow::MerchantsAccountDelete + | Flow::MerchantTransferKey | Flow::MerchantAccountList => Self::MerchantAccount, Flow::RoutingCreateConfig @@ -233,6 +234,7 @@ impl From<Flow> for ApiIdentifier { | Flow::CreateUserAuthenticationMethod | Flow::UpdateUserAuthenticationMethod | Flow::ListUserAuthenticationMethods + | Flow::UserTransferKey | Flow::GetSsoAuthUrl | Flow::SignInWithSso | Flow::AuthSelect => Self::User, diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 7e55393cc57..29935bc8ab7 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -895,3 +895,18 @@ pub async fn terminate_auth_select( )) .await } + +pub async fn transfer_user_key(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::UserTransferKey; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, _, _, _| user_core::transfer_user_key_store_keymanager(state), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs index 176b88b3f5b..151ae61f5fe 100644 --- a/crates/router/src/types/domain/types.rs +++ b/crates/router/src/types/domain/types.rs @@ -1,3 +1,18 @@ +use common_utils::types::keymanager::KeyManagerState; pub use hyperswitch_domain_models::type_encryption::{ decrypt, encrypt, encrypt_optional, AsyncLift, Lift, TypeEncryption, }; + +impl From<&crate::SessionState> for KeyManagerState { + fn from(state: &crate::SessionState) -> Self { + let conf = state.conf.key_manager.get_inner(); + Self { + url: conf.url.clone(), + client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout, + #[cfg(feature = "keymanager_mtls")] + cert: conf.cert.clone(), + #[cfg(feature = "keymanager_mtls")] + ca: conf.ca.clone(), + } + } +} diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index d5100c89c19..c4c67796d46 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -6,6 +6,8 @@ use api_models::{ use common_enums::TokenPurpose; #[cfg(not(feature = "v2"))] use common_utils::id_type; +#[cfg(feature = "keymanager_create")] +use common_utils::types::keymanager::{EncryptionCreateRequest, Identifier}; use common_utils::{crypto::Encryptable, errors::CustomResult, new_type::MerchantName, pii}; use diesel_models::{ enums::{TotpStatus, UserStatus}, @@ -971,6 +973,19 @@ impl UserFromStorage { .change_context(UserErrors::InternalServerError)?, created_at: common_utils::date_time::now(), }; + + #[cfg(feature = "keymanager_create")] + { + common_utils::keymanager::create_key_in_key_manager( + &state.into(), + EncryptionCreateRequest { + identifier: Identifier::User(key_store.user_id.clone()), + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + } + state .global_store .insert_user_key_store(key_store, &master_key.to_vec().into()) diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 2fef21d420c..8ff019f9b5f 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -81,6 +81,8 @@ pub enum Flow { MerchantConnectorsDelete, /// Merchant Connectors list flow. MerchantConnectorsList, + /// Merchant Transfer Keys + MerchantTransferKey, /// ConfigKey create flow. ConfigKeyCreate, /// ConfigKey fetch flow. @@ -316,6 +318,8 @@ pub enum Flow { UserSignUpWithMerchantId, /// User Sign In UserSignIn, + /// User transfer key + UserTransferKey, /// User connect account UserConnectAccount, /// Upsert Decision Manager Config diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 2f1aa1dbbd8..f38cd05e7c4 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -9,6 +9,9 @@ traces_enabled = true metrics_enabled = true ignore_errors = false +[key_manager] +url = "http://localhost:5000" + [master_database] username = "postgres" password = "postgres" @@ -339,4 +342,4 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
2024-06-07T09:50:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> This PR adds support to - Create Key for every User and Merchant during User and Merchant Account Create. - Add an API to transfer Keys to KeyManager - Add MTLS for KeyManager Client ### Additional Changes - [x] This PR modifies application configuration/environment variables ## 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). --> - Create Key in Key Manager for every merchant ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### Tests for Create a Merchant - ```bash 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_1720435957", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "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_version": "1.0.1", "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" } ] }' ``` - Verify `/key/create` to Keymanager was succeeded. The response status of `keymanager_response` should be 200 <img width="1334" alt="Screenshot 2024-07-11 at 5 01 27 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/95dcf641-0908-4f4d-8803-53e435906220"> ### Create Key for User - Signin with the account and password ``` curl --location 'http://localhost:8080/user/v2/signin?token_only=true' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "gagagagag@gagagagagag.com", "password": "gagagagag@1234" }' ``` - Begin TOTP flow ``` curl --location 'http://localhost:8080/user/2fa/totp/begin' \ --header 'Authorization: Bearer spt' ``` - Verify that call to `/key/create` is successful in the logs ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
998ce02ebc1eed10e426987d1af9c02d1f1735fe
juspay/hyperswitch
juspay__hyperswitch-5242
Bug: add an api to migrate the payment method This is the API that will be used to migrate card details and associated data stored in another service to Hyperswitch. How does this API differ from the existing payment method creation API? 1. It takes masked card details as input with valid first six and last four card numbers. 2. It also accepts `connector_mandate_details` and `network_transaction_id` if present. If the masked card number is provided as input, a payment method entry is created in Hyperswitch, and no data is stored in the locker. If a valid card number is present, the card details are stored in the locker, the same as in the save card flow.
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index cb268262fbc..5b360e39956 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1229,6 +1229,8 @@ pub struct ConnectorAgnosticMitChoice { impl common_utils::events::ApiEventMetric for ConnectorAgnosticMitChoice {} +impl common_utils::events::ApiEventMetric for payment_methods::PaymentMethodMigrate {} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ExtendedCardInfoConfig { /// Merchant public key diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index c8826c02089..7b33e3dfeab 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -75,6 +75,128 @@ pub struct PaymentMethodCreate { /// Payment method data to be passed in case of client /// based flow pub payment_method_data: Option<PaymentMethodCreateData>, + + /// The billing details of the payment method + #[schema(value_type = Option<Address>)] + pub billing: Option<payments::Address>, + + #[serde(skip_deserializing)] + /// The connector mandate details of the payment method, this is added only for cards migration + /// api and is skipped during deserialization of the payment method create request as this + /// it should not be passed in the request + pub connector_mandate_details: Option<PaymentsMandateReference>, + + #[serde(skip_deserializing)] + /// The transaction id of a CIT (customer initiated transaction) associated with the payment method, + /// this is added only for cards migration api and is skipped during deserialization of the + /// payment method create request as it should not be passed in the request + pub network_transaction_id: Option<String>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +/// This struct is only used by and internal api to migrate payment method +pub struct PaymentMethodMigrate { + /// Merchant id + pub merchant_id: String, + + /// The type of payment method use for the payment. + pub payment_method: Option<api_enums::PaymentMethod>, + + /// This is a sub-category of payment method. + pub payment_method_type: Option<api_enums::PaymentMethodType>, + + /// The name of the bank/ provider issuing the payment method to the end user + pub payment_method_issuer: Option<String>, + + /// A standard code representing the issuer of payment method + pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, + + /// Card Details + pub card: Option<MigrateCardDetail>, + + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + pub metadata: Option<pii::SecretSerdeValue>, + + /// The unique identifier of the customer. + pub customer_id: Option<id_type::CustomerId>, + + /// The card network + pub card_network: Option<String>, + + /// Payment method details from locker + #[cfg(feature = "payouts")] + pub bank_transfer: Option<payouts::Bank>, + + /// Payment method details from locker + #[cfg(feature = "payouts")] + pub wallet: Option<payouts::Wallet>, + + /// Payment method data to be passed in case of client + /// based flow + pub payment_method_data: Option<PaymentMethodCreateData>, + + /// The billing details of the payment method + pub billing: Option<payments::Address>, + + /// The connector mandate details of the payment method + pub connector_mandate_details: Option<PaymentsMandateReference>, + + // The CIT (customer initiated transaction) transaction id associated with the payment method + pub network_transaction_id: Option<String>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentsMandateReference(pub HashMap<String, PaymentsMandateReferenceRecord>); + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentsMandateReferenceRecord { + pub connector_mandate_id: String, + pub payment_method_type: Option<common_enums::PaymentMethodType>, + pub original_payment_authorized_amount: Option<i64>, + pub original_payment_authorized_currency: Option<common_enums::Currency>, +} + +impl PaymentMethodCreate { + pub fn get_payment_method_create_from_payment_method_migrate( + card_number: CardNumber, + payment_method_migrate: &PaymentMethodMigrate, + ) -> Self { + let card_details = + payment_method_migrate + .card + .as_ref() + .map(|payment_method_migrate_card| CardDetail { + card_number, + card_exp_month: payment_method_migrate_card.card_exp_month.clone(), + card_exp_year: payment_method_migrate_card.card_exp_year.clone(), + card_holder_name: payment_method_migrate_card.card_holder_name.clone(), + nick_name: payment_method_migrate_card.nick_name.clone(), + card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), + card_network: payment_method_migrate_card.card_network.clone(), + card_issuer: payment_method_migrate_card.card_issuer.clone(), + card_type: payment_method_migrate_card.card_type.clone(), + }); + + Self { + customer_id: payment_method_migrate.customer_id.clone(), + payment_method: payment_method_migrate.payment_method, + payment_method_type: payment_method_migrate.payment_method_type, + payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(), + payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code, + metadata: payment_method_migrate.metadata.clone(), + payment_method_data: payment_method_migrate.payment_method_data.clone(), + connector_mandate_details: payment_method_migrate.connector_mandate_details.clone(), + client_secret: None, + billing: payment_method_migrate.billing.clone(), + card: card_details, + card_network: payment_method_migrate.card_network.clone(), + #[cfg(feature = "payouts")] + bank_transfer: payment_method_migrate.bank_transfer.clone(), + #[cfg(feature = "payouts")] + wallet: payment_method_migrate.wallet.clone(), + network_transaction_id: payment_method_migrate.network_transaction_id.clone(), + } + } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] @@ -139,6 +261,43 @@ pub struct CardDetail { pub card_type: Option<String>, } +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct MigrateCardDetail { + /// Card Number + #[schema(value_type = String,example = "4111111145551142")] + pub card_number: masking::Secret<String>, + + /// Card Expiry Month + #[schema(value_type = String,example = "10")] + pub card_exp_month: masking::Secret<String>, + + /// Card Expiry Year + #[schema(value_type = String,example = "25")] + pub card_exp_year: masking::Secret<String>, + + /// Card Holder Name + #[schema(value_type = String,example = "John Doe")] + pub card_holder_name: Option<masking::Secret<String>>, + + /// 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, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetailUpdate { diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index d968e62bea8..24ba06bcf36 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -130,6 +130,9 @@ pub async fn call_to_locker( card_network: card.card_brand, client_secret: None, payment_method_data: None, + billing: None, + connector_mandate_details: None, + network_transaction_id: None, }; let add_card_result = cards::add_card_hs( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 495d85d5b36..ef1fa51442b 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -95,6 +95,7 @@ pub async fn create_payment_method( network_transaction_id: Option<String>, storage_scheme: MerchantStorageScheme, payment_method_billing_address: Option<Encryption>, + card_scheme: Option<String>, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { let customer = db .find_customer_by_customer_id_merchant_id( @@ -123,7 +124,7 @@ pub async fn create_payment_method( payment_method: req.payment_method, payment_method_type: req.payment_method_type, payment_method_issuer: req.payment_method_issuer.clone(), - scheme: req.card_network.clone(), + scheme: req.card_network.clone().or(card_scheme), metadata: pm_metadata.map(Secret::new), payment_method_data, connector_mandate_details, @@ -244,7 +245,7 @@ pub async fn get_or_insert_payment_method( insert_payment_method( db, resp, - req, + &req, key_store, &merchant_account.merchant_id, customer_id, @@ -252,7 +253,7 @@ pub async fn get_or_insert_payment_method( None, locker_id, None, - None, + req.network_transaction_id.clone(), merchant_account.storage_scheme, None, ) @@ -266,6 +267,314 @@ pub async fn get_or_insert_payment_method( } } +pub async fn migrate_payment_method( + state: routes::SessionState, + req: api::PaymentMethodMigrate, +) -> errors::RouterResponse<api::PaymentMethodResponse> { + let merchant_id = &req.merchant_id; + 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(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let card_details = req.card.as_ref().get_required_value("card")?; + + let card_number_validation_result = + cards::CardNumber::from_str(card_details.card_number.peek()); + + if let Some(connector_mandate_details) = &req.connector_mandate_details { + helpers::validate_merchant_connector_ids_in_connector_mandate_details( + &*state.store, + &key_store, + connector_mandate_details, + merchant_id, + ) + .await?; + }; + + match card_number_validation_result { + Ok(card_number) => { + let payment_method_create_request = + api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate( + card_number, + &req, + ); + get_client_secret_or_add_payment_method( + state, + payment_method_create_request, + &merchant_account, + &key_store, + ) + .await + } + Err(card_validation_error) => { + logger::debug!("Card number to be migrated is invalid, skip saving in locker {card_validation_error}"); + skip_locker_call_and_migrate_payment_method( + state, + &req, + merchant_id.into(), + &key_store, + &merchant_account, + ) + .await + } + } +} + +pub async fn skip_locker_call_and_migrate_payment_method( + state: routes::SessionState, + req: &api::PaymentMethodMigrate, + merchant_id: String, + key_store: &domain::MerchantKeyStore, + merchant_account: &domain::MerchantAccount, +) -> errors::RouterResponse<api::PaymentMethodResponse> { + let db = &*state.store; + let customer_id = req.customer_id.clone().get_required_value("customer_id")?; + + // In this case, since we do not have valid card details, recurring payments can only be done through connector mandate details. + let connector_mandate_details_req = req + .connector_mandate_details + .clone() + .get_required_value("connector mandate details")?; + + let connector_mandate_details = serde_json::to_value(&connector_mandate_details_req) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse connector mandate details")?; + + let payment_method_billing_address = create_encrypted_data(key_store, req.billing.clone()) + .await + .map(|details| details.into()); + + let customer = db + .find_customer_by_customer_id_merchant_id( + &customer_id, + &merchant_id, + key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + + let card = if let Some(card_details) = &req.card { + helpers::validate_card_expiry(&card_details.card_exp_month, &card_details.card_exp_year)?; + let card_number = card_details.card_number.clone(); + + let (card_isin, last4_digits) = get_card_bin_and_last4_digits_for_masked_card( + card_number.peek(), + ) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid card number".to_string(), + })?; + + if card_details.card_issuer.is_some() + && card_details.card_network.is_some() + && card_details.card_type.is_some() + && card_details.card_issuing_country.is_some() + { + Some(api::CardDetailFromLocker { + scheme: card_details + .card_network + .clone() + .or(card_details.card_network.clone()) + .map(|card_network| card_network.to_string()), + last4_digits: Some(last4_digits.clone()), + issuer_country: card_details + .card_issuing_country + .clone() + .or(card_details.card_issuing_country.clone()), + card_number: None, + expiry_month: Some(card_details.card_exp_month.clone()), + expiry_year: Some(card_details.card_exp_year.clone()), + card_token: None, + card_fingerprint: None, + card_holder_name: card_details.card_holder_name.clone(), + nick_name: card_details.nick_name.clone(), + card_isin: Some(card_isin.clone()), + card_issuer: card_details + .card_issuer + .clone() + .or(card_details.card_issuer.clone()), + card_network: card_details + .card_network + .clone() + .or(card_details.card_network.clone()), + card_type: card_details + .card_type + .clone() + .or(card_details.card_type.clone()), + saved_to_locker: false, + }) + } else { + Some( + db.get_card_info(&card_isin) + .await + .map_err(|error| services::logger::error!(card_info_error=?error)) + .ok() + .flatten() + .map(|card_info| { + logger::debug!("Fetching bin details"); + api::CardDetailFromLocker { + scheme: card_details + .card_network + .clone() + .or(card_info.card_network.clone()) + .map(|card_network| card_network.to_string()), + last4_digits: Some(last4_digits.clone()), + issuer_country: card_details + .card_issuing_country + .clone() + .or(card_info.card_issuing_country), + card_number: None, + expiry_month: Some(card_details.card_exp_month.clone()), + expiry_year: Some(card_details.card_exp_year.clone()), + card_token: None, + card_fingerprint: None, + card_holder_name: card_details.card_holder_name.clone(), + nick_name: card_details.nick_name.clone(), + card_isin: Some(card_isin.clone()), + card_issuer: card_details.card_issuer.clone().or(card_info.card_issuer), + card_network: card_details + .card_network + .clone() + .or(card_info.card_network), + card_type: card_details.card_type.clone().or(card_info.card_type), + saved_to_locker: false, + } + }) + .unwrap_or_else(|| { + logger::debug!("Failed to fetch bin details"); + api::CardDetailFromLocker { + scheme: card_details + .card_network + .clone() + .map(|card_network| card_network.to_string()), + last4_digits: Some(last4_digits.clone()), + issuer_country: card_details.card_issuing_country.clone(), + card_number: None, + expiry_month: Some(card_details.card_exp_month.clone()), + expiry_year: Some(card_details.card_exp_year.clone()), + card_token: None, + card_fingerprint: None, + card_holder_name: card_details.card_holder_name.clone(), + nick_name: card_details.nick_name.clone(), + card_isin: Some(card_isin.clone()), + card_issuer: card_details.card_issuer.clone(), + card_network: card_details.card_network.clone(), + card_type: card_details.card_type.clone(), + saved_to_locker: false, + } + }), + ) + } + } else { + None + }; + + let payment_method_card_details = card + .as_ref() + .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + + let payment_method_data_encrypted = + create_encrypted_data(key_store, payment_method_card_details) + .await + .map(|details| details.into()); + + let payment_method_metadata: Option<serde_json::Value> = + req.metadata.as_ref().map(|data| data.peek()).cloned(); + + let payment_method_id = generate_id(consts::ID_LENGTH, "pm"); + + let current_time = common_utils::date_time::now(); + + let response = db + .insert_payment_method( + storage::PaymentMethodNew { + customer_id: customer_id.to_owned(), + merchant_id: merchant_id.to_string(), + payment_method_id: payment_method_id.to_string(), + locker_id: None, + payment_method: req.payment_method, + payment_method_type: req.payment_method_type, + payment_method_issuer: req.payment_method_issuer.clone(), + scheme: req.card_network.clone(), + metadata: payment_method_metadata.map(Secret::new), + payment_method_data: payment_method_data_encrypted, + connector_mandate_details: Some(connector_mandate_details), + customer_acceptance: None, + client_secret: None, + status: enums::PaymentMethodStatus::Active, + network_transaction_id: None, + payment_method_issuer_code: None, + accepted_currency: None, + token: None, + cardholder_name: None, + issuer_name: None, + issuer_country: None, + payer_country: None, + is_stored: None, + swift_code: None, + direct_debit_token: None, + created_at: current_time, + last_modified: current_time, + last_used_at: current_time, + payment_method_billing_address, + updated_by: None, + }, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; + + logger::debug!("Payment method inserted in db"); + + if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { + let _ = set_default_payment_method( + &*state.store, + merchant_id.to_string(), + key_store.clone(), + &customer_id, + payment_method_id.to_owned(), + merchant_account.storage_scheme, + ) + .await + .map_err(|err| logger::error!(error=?err,"Failed to set the payment method as default")); + } + Ok(services::api::ApplicationResponse::Json( + api::PaymentMethodResponse::foreign_from((card, response)), + )) +} + +pub fn get_card_bin_and_last4_digits_for_masked_card( + masked_card_number: &str, +) -> Result<(String, String), cards::CardNumberValidationErr> { + let last4_digits = masked_card_number + .chars() + .rev() + .take(4) + .collect::<String>() + .chars() + .rev() + .collect::<String>(); + + let card_isin = masked_card_number.chars().take(6).collect::<String>(); + + cards::validate::validate_card_number_chars(&card_isin) + .and_then(|_| cards::validate::validate_card_number_chars(&last4_digits))?; + + Ok((card_isin, last4_digits)) +} + #[instrument(skip_all)] pub async fn get_client_secret_or_add_payment_method( state: routes::SessionState, @@ -282,6 +591,17 @@ pub async fn get_client_secret_or_add_payment_method( #[cfg(feature = "payouts")] let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some(); + let payment_method_billing_address = create_encrypted_data(key_store, req.billing.clone()) + .await + .map(|details| details.into()); + + let connector_mandate_details = req + .connector_mandate_details + .clone() + .map(serde_json::to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError)?; + if condition { Box::pin(add_payment_method(state, req, merchant_account, key_store)).await } else { @@ -298,10 +618,11 @@ pub async fn get_client_secret_or_add_payment_method( None, None, key_store, - None, + connector_mandate_details, Some(enums::PaymentMethodStatus::AwaitingData), None, merchant_account.storage_scheme, + payment_method_billing_address, None, ) .await?; @@ -322,7 +643,7 @@ pub async fn get_client_secret_or_add_payment_method( } Ok(services::api::ApplicationResponse::Json( - api::PaymentMethodResponse::foreign_from(res), + api::PaymentMethodResponse::foreign_from((None, res)), )) } } @@ -544,6 +865,16 @@ pub async fn add_payment_method( let merchant_id = &merchant_account.merchant_id; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; let payment_method = req.payment_method.get_required_value("payment_method")?; + let payment_method_billing_address = create_encrypted_data(key_store, req.billing.clone()) + .await + .map(|details| details.into()); + + let connector_mandate_details = req + .connector_mandate_details + .clone() + .map(serde_json::to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError)?; let response = match payment_method { #[cfg(feature = "payouts")] @@ -567,11 +898,20 @@ pub async fn add_payment_method( }, api_enums::PaymentMethod::Card => match req.card.clone() { Some(card) => { - helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?; + let mut card_details = card; + card_details = helpers::populate_bin_details_for_payment_method_create( + card_details.clone(), + db, + ) + .await; + helpers::validate_card_expiry( + &card_details.card_exp_month, + &card_details.card_exp_year, + )?; Box::pin(add_card_to_locker( &state, req.clone(), - &card, + &card_details, &customer_id, merchant_account, None, @@ -731,17 +1071,17 @@ pub async fn add_payment_method( let pm = insert_payment_method( db, &resp, - req, + &req, key_store, merchant_id, &customer_id, pm_metadata.cloned(), None, locker_id, - None, - None, + connector_mandate_details, + req.network_transaction_id.clone(), merchant_account.storage_scheme, - None, + payment_method_billing_address, ) .await?; @@ -756,7 +1096,7 @@ pub async fn add_payment_method( pub async fn insert_payment_method( db: &dyn db::StorageInterface, resp: &api::PaymentMethodResponse, - req: api::PaymentMethodCreate, + req: &api::PaymentMethodCreate, key_store: &domain::MerchantKeyStore, merchant_id: &str, customer_id: &id_type::CustomerId, @@ -770,7 +1110,7 @@ pub async fn insert_payment_method( ) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp .card - .as_ref() + .clone() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); let pm_data_encrypted = create_encrypted_data(key_store, pm_card_details) .await @@ -778,7 +1118,7 @@ pub async fn insert_payment_method( create_payment_method( db, - &req, + req, customer_id, &resp.payment_method_id, locker_id, @@ -792,6 +1132,10 @@ pub async fn insert_payment_method( network_transaction_id, storage_scheme, payment_method_billing_address, + resp.card.clone().and_then(|card| { + card.card_network + .map(|card_network| card_network.to_string()) + }), ) .await } @@ -904,6 +1248,9 @@ pub async fn update_customer_payment_method( client_secret: pm.client_secret.clone(), payment_method_data: None, card_network: None, + billing: None, + connector_mandate_details: None, + network_transaction_id: None, }; new_pm.validate()?; @@ -1135,7 +1482,7 @@ pub async fn add_card_to_locker( errors::VaultError, > { metrics::STORED_TO_LOCKER.add(&metrics::CONTEXT, 1, &[]); - let add_card_to_hs_resp = common_utils::metrics::utils::record_operation_time( + let add_card_to_hs_resp = Box::pin(common_utils::metrics::utils::record_operation_time( async { add_card_hs( state, @@ -1162,7 +1509,7 @@ pub async fn add_card_to_locker( &metrics::CARD_ADD_TIME, &metrics::CONTEXT, &[router_env::opentelemetry::KeyValue::new("locker", "rust")], - ) + )) .await?; logger::debug!("card added to hyperswitch-card-vault"); @@ -3677,12 +4024,8 @@ pub async fn get_card_details_with_locker_fallback( }); Ok(if let Some(mut crd) = card_decrypted { - if crd.saved_to_locker { - crd.scheme.clone_from(&pm.scheme); - Some(crd) - } else { - None - } + crd.scheme.clone_from(&pm.scheme); + Some(crd) } else { logger::debug!( "Getting card details from locker as it is not found in payment methods table" diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 887c02dd023..6bfadabdb35 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -348,7 +348,10 @@ pub fn mk_add_card_response_hs( let card_isin = card_number.get_card_isin(); let card = api::CardDetailFromLocker { - scheme: None, + scheme: card + .card_network + .clone() + .map(|card_network| card_network.to_string()), last4_digits: Some(last4_digits), issuer_country: card.card_issuing_country, card_number: Some(card.card_number.clone()), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index c19480f1d56..745a69a1f56 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1385,6 +1385,9 @@ pub(crate) async fn get_payment_method_create_request( .map(|card_network| card_network.to_string()), client_secret: None, payment_method_data: None, + billing: None, + connector_mandate_details: None, + network_transaction_id: None, }; Ok(payment_method_request) } @@ -1404,6 +1407,9 @@ pub(crate) async fn get_payment_method_create_request( card_network: None, client_secret: None, payment_method_data: None, + billing: None, + connector_mandate_details: None, + network_transaction_id: None, }; Ok(payment_method_request) @@ -4074,6 +4080,63 @@ pub async fn get_additional_payment_data( } } +pub async fn populate_bin_details_for_payment_method_create( + card_details: api_models::payment_methods::CardDetail, + db: &dyn StorageInterface, +) -> api_models::payment_methods::CardDetail { + let card_isin: Option<_> = Some(card_details.card_number.get_card_isin()); + if card_details.card_issuer.is_some() + && card_details.card_network.is_some() + && card_details.card_type.is_some() + && card_details.card_issuing_country.is_some() + { + api::CardDetail { + card_issuer: card_details.card_issuer.to_owned(), + card_network: card_details.card_network.clone(), + card_type: card_details.card_type.to_owned(), + card_issuing_country: card_details.card_issuing_country.to_owned(), + card_exp_month: card_details.card_exp_month.clone(), + card_exp_year: card_details.card_exp_year.clone(), + card_holder_name: card_details.card_holder_name.clone(), + card_number: card_details.card_number.clone(), + nick_name: card_details.nick_name.clone(), + } + } else { + let card_info = card_isin + .clone() + .async_and_then(|card_isin| async move { + db.get_card_info(&card_isin) + .await + .map_err(|error| services::logger::error!(card_info_error=?error)) + .ok() + }) + .await + .flatten() + .map(|card_info| api::CardDetail { + card_issuer: card_info.card_issuer, + card_network: card_info.card_network.clone(), + card_type: card_info.card_type, + card_issuing_country: card_info.card_issuing_country, + card_exp_month: card_details.card_exp_month.clone(), + card_exp_year: card_details.card_exp_year.clone(), + card_holder_name: card_details.card_holder_name.clone(), + card_number: card_details.card_number.clone(), + nick_name: card_details.nick_name.clone(), + }); + card_info.unwrap_or_else(|| api::CardDetail { + card_issuer: None, + card_network: None, + card_type: None, + card_issuing_country: None, + card_exp_month: card_details.card_exp_month.clone(), + card_exp_year: card_details.card_exp_year.clone(), + card_holder_name: card_details.card_holder_name.clone(), + card_number: card_details.card_number.clone(), + nick_name: card_details.nick_name.clone(), + }) + } +} + pub fn validate_customer_access( payment_intent: &PaymentIntent, auth_flow: services::AuthFlow, @@ -5057,3 +5120,36 @@ pub async fn override_setup_future_usage_to_on_session<F: Clone>( }; Ok(()) } + +pub async fn validate_merchant_connector_ids_in_connector_mandate_details( + db: &dyn StorageInterface, + key_store: &domain::MerchantKeyStore, + connector_mandate_details: &api_models::payment_methods::PaymentsMandateReference, + merchant_id: &str, +) -> CustomResult<(), errors::ApiErrorResponse> { + let merchant_connector_account_list = db + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_id, + true, + key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + + let merchant_connector_ids: Vec<String> = merchant_connector_account_list + .iter() + .map(|merchant_connector_account| merchant_connector_account.merchant_connector_id.clone()) + .collect(); + + for merchant_connector_id in connector_mandate_details.0.keys() { + if !merchant_connector_ids.contains(merchant_connector_id) { + Err(errors::ApiErrorResponse::InvalidDataValue { + field_name: "merchant_connector_id", + }) + .attach_printable_lazy(|| { + format!("{merchant_connector_id} invalid merchant connector id in connector_mandate_details") + })? + } + } + Ok(()) +} diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index f63278cddc4..3fb67abd57e 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -318,6 +318,10 @@ where network_transaction_id, merchant_account.storage_scheme, encrypted_payment_method_billing_address, + resp.card.and_then(|card| { + card.card_network + .map(|card_network| card_network.to_string()) + }), ) .await } else { @@ -397,7 +401,7 @@ where payment_methods::cards::insert_payment_method( db, &resp, - payment_method_create_request.clone(), + &payment_method_create_request.clone(), key_store, &merchant_account.merchant_id, &customer_id, @@ -602,6 +606,10 @@ where network_transaction_id, merchant_account.storage_scheme, encrypted_payment_method_billing_address, + resp.card.and_then(|card| { + card.card_network + .map(|card_network| card_network.to_string()) + }), ) .await?; }; diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index ba00370e881..f68a5271fd7 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -391,6 +391,9 @@ pub async fn save_payout_data_to_locker( card_network: None, client_secret: None, payment_method_data: None, + billing: None, + connector_mandate_details: None, + network_transaction_id: None, }; let pm_data = card_isin @@ -472,6 +475,9 @@ pub async fn save_payout_data_to_locker( card_network: None, client_secret: None, payment_method_data: None, + billing: None, + connector_mandate_details: None, + network_transaction_id: None, }, ) }; @@ -495,6 +501,7 @@ pub async fn save_payout_data_to_locker( None, merchant_account.storage_scheme, None, + None, ) .await?; } diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 508b9e8ef8b..d3393b5b1f7 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -478,7 +478,6 @@ async fn store_bank_details_in_payment_methods( last_used_at: now, connector_mandate_details: None, customer_acceptance: None, - network_transaction_id: None, client_secret: None, payment_method_billing_address: None, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 4fad6f863e9..ba94879cd68 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -931,6 +931,9 @@ impl PaymentMethods { .route(web::post().to(create_payment_method_api)) .route(web::get().to(list_payment_method_api)), // TODO : added for sdk compatibility for now, need to deprecate this later ) + .service( + web::resource("/migrate").route(web::post().to(migrate_payment_method_api)), + ) .service( web::resource("/collect").route(web::post().to(initiate_pm_collect_link_flow)), ) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index fb5be71b521..56e8751a979 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -93,6 +93,7 @@ impl From<Flow> for ApiIdentifier { Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates, Flow::PaymentMethodsCreate + | Flow::PaymentMethodsMigrate | Flow::PaymentMethodsList | Flow::CustomerPaymentMethodsList | Flow::PaymentMethodsRetrieve diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index bc748572150..8ff6e48237c 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -46,6 +46,26 @@ pub async fn create_payment_method_api( .await } +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))] +pub async fn migrate_payment_method_api( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<payment_methods::PaymentMethodMigrate>, +) -> HttpResponse { + let flow = Flow::PaymentMethodsMigrate; + + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _, req, _| async move { Box::pin(cards::migrate_payment_method(state, req)).await }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))] pub async fn save_payment_method_api( state: web::Data<AppState>, diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index ef92c099735..77873503d6e 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -4,9 +4,10 @@ pub use api_models::payment_methods::{ GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, - PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse, - PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, - TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, + PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate, + PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, + TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, + TokenizedWalletValue2, }; use error_stack::report; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 8f3ef929b1d..49afaf2e474 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -80,15 +80,25 @@ impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType } } -impl ForeignFrom<diesel_models::PaymentMethod> for payment_methods::PaymentMethodResponse { - fn foreign_from(item: diesel_models::PaymentMethod) -> Self { +impl + ForeignFrom<( + Option<payment_methods::CardDetailFromLocker>, + diesel_models::PaymentMethod, + )> for payment_methods::PaymentMethodResponse +{ + fn foreign_from( + (card_details, item): ( + Option<payment_methods::CardDetailFromLocker>, + diesel_models::PaymentMethod, + ), + ) -> Self { Self { merchant_id: item.merchant_id, customer_id: Some(item.customer_id), payment_method_id: item.payment_method_id, payment_method: item.payment_method, payment_method_type: item.payment_method_type, - card: None, + card: card_details, recurring_enabled: false, installment_payment_enabled: false, payment_experience: None, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 733876d0ee6..2fef21d420c 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -111,6 +111,8 @@ pub enum Flow { MandatesList, /// Payment methods create flow. PaymentMethodsCreate, + /// Payment methods migrate flow. + PaymentMethodsMigrate, /// Payment methods list flow. PaymentMethodsList, /// Payment method save flow
2024-07-03T09:22:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This is the API that will be used to migrate card details and associated data stored in another service to Hyperswitch. How does this API differ from the existing payment method creation API? 1. It takes masked card details as input with valid first six and last four card numbers. 2. It also accepts `connector_mandate_details` and `network_transaction_id` if present. If the masked card number is provided as input, a payment method entry is created in Hyperswitch, and no data is stored in the locker. If a valid card number is present, the card details are stored in the locker, the same as in the save card flow. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant connector account for cybersource ### Test on_session saved payment -> Crate a payment with `setup_future_usage: on_session` ``` { "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_{{$timestamp}}", "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": "http://127.0.0.1:4040", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "838" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "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": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` <img width="1105" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/35151830-ba01-45dc-992b-aa7482e4c455"> -> Create payment with confirm false for the same customer ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_YsyZ2fWnqbVilsKF7TKSUd0Wuwdgf2vvxQzQVIBaCqeSGU9XRY3Pjmk9mLjNsaRm' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1720508543" }' ``` <img width="1204" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/5acdd2fd-370b-4e64-a768-e3b44839814b"> -> Do payment method list with the client_secret ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_kGh4EiDR0G5PliuQVvcn_secret_SGva6IBvDkYjWGzkORVU' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cad52206021b4f44932e750bb3afb1d4' ``` <img width="1190" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/ed3dd62c-f05b-4048-aad4-eda74bf32f5d"> -> Confirm the payment with the payment_token ``` curl --location 'http://localhost:8080/payments/pay_kGh4EiDR0G5PliuQVvcn/confirm' \ --header 'api-key: pk_dev_cad52206021b4f44932e750bb3afb1d4' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_8hR80yevZdbKLaW2rrY4", "client_secret": "pay_kGh4EiDR0G5PliuQVvcn_secret_SGva6IBvDkYjWGzkORVU", "payment_method": "card", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } } }' ``` <img width="1217" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/fdd4fc09-0acc-4e79-b1e9-5fd874af99a3"> ### Test off_session saved payment -> Create payment with setup_future_usage: off_session ``` { "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_{{$timestamp}}", "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": "off_session", "return_url": "http://127.0.0.1:4040", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "838" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "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": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` <img width="1085" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/233766ef-b390-4b0a-94ef-fbcb562af3e7"> -> Create a payment and payment method list with the client_secret ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_YsyZ2fWnqbVilsKF7TKSUd0Wuwdgf2vvxQzQVIBaCqeSGU9XRY3Pjmk9mLjNsaRm' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1720509577" }' ``` ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_4QhSPVojFUcfdK2HxncL_secret_4EwPFiS6npXTWyv9eQd9' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cad52206021b4f44932e750bb3afb1d4' ``` <img width="1024" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/45bd6716-7aae-426f-81b2-0ee9e8a2c7e7"> -> Confirm the payment with token ``` curl --location 'http://localhost:8080/payments/pay_JuR2NJ9Xw3aOwVKBF7UL/confirm' \ --header 'api-key: pk_dev_cad52206021b4f44932e750bb3afb1d4' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_aQehaaeF9Z6HSgPjCrPJ", "client_secret": "pay_JuR2NJ9Xw3aOwVKBF7UL_secret_k7d6s0Wqn8qcY6iNB2Ti", "payment_method": "card", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } } }' ``` <img width="1051" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a59bef5f-eebf-4dfd-ba44-8c62fec2ea51"> ### Test payment method migration api with connector mandate details -> use the appropriate `connector_mandate_id` save the above payment method for a customer ``` curl --location 'http://localhost:8080/payment_methods/merchant_1720508278/migrate' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "payment_method": "card", "card": { "card_number": "424242xxxxxx4242", "card_exp_month": "10", "card_exp_year": "26", "nick_name": "Joh" }, "customer_id": "cu_1720456680", "connector_mandate_details": { "mca_5opSKiHdcALo37nP7Gl": { "connector_mandate_id": "connector_mandate_id", "original_payment_authorized_amount": 6560, "original_payment_authorized_currency": "USD" } } } ' ``` -> Create a payment for the customer with confirm false and perform payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_YsyZ2fWnqbVilsKF7TKSUd0Wuwdgf2vvxQzQVIBaCqeSGU9XRY3Pjmk9mLjNsaRm' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "setup_future_usage": "off_session", "customer_id": "cu_1720510734" }' ``` -> Payment method list with the client secret ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_nVu4pFzZkJyzIpsZzogt_secret_RU1A52ZevqUfCHsnxSQo' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cad52206021b4f44932e750bb3afb1d4' ``` <img width="1096" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38866b0f-02d7-4f04-ab70-7aaa30864322"> -> Confirm the payment with the token, in this case payment will go through even without the card details as the connector mandate details are present ``` curl --location 'http://localhost:8080/payments/pay_nVu4pFzZkJyzIpsZzogt/confirm' \ --header 'api-key: pk_dev_cad52206021b4f44932e750bb3afb1d4' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_vm9vZGkoxH2dcWUpsHou", "client_secret": "pay_nVu4pFzZkJyzIpsZzogt_secret_RU1A52ZevqUfCHsnxSQo", "payment_method": "card", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } } }' ``` ### Test payment method migration api with network_transaction_id ``` curl --location 'http://localhost:8080/payment_methods/migrate' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "payment_method": "card", "merchant_id": "merchant_1720508278", "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "26", "nick_name": "Joh" }, "customer_id": "cu_1720514044", "network_transaction_id": "network_transaction_id", "connector_mandate_details": { "mca_jqWPPZvDec4Y6KLWzgXe": { "connector_mandate_id": "connector_mandate_id", "original_payment_authorized_amount": 6560, "original_payment_authorized_currency": "USD" } } } ' ``` -> Enable the is_connector_agnostic_mit_enabled for the business profile ``` curl --location 'http://localhost:8080/account/merchant_1720508278/business_profile/pro_7cMwkt3td8JW7UcwKcAq' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "is_connector_agnostic_mit_enabled": true }' ``` -> Create payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_YsyZ2fWnqbVilsKF7TKSUd0Wuwdgf2vvxQzQVIBaCqeSGU9XRY3Pjmk9mLjNsaRm' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "setup_future_usage": "off_session", "customer_id": "cu_1720514044" }' ``` -> list payment methods for customer ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_CjuYS0q3tS2huyVZdhQy_secret_AY0QHOox9y6WWeMA0Q07' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cad52206021b4f44932e750bb3afb1d4' ``` <img width="1138" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/028c415c-2f80-4703-aed3-6281f8a5e7df"> -> Confirm the payment with the token ``` curl --location 'http://localhost:8080/payments/pay_CjuYS0q3tS2huyVZdhQy/confirm' \ --header 'api-key: pk_dev_cad52206021b4f44932e750bb3afb1d4' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_a0AggkExh1ReYxueRT6n", "client_secret": "pay_CjuYS0q3tS2huyVZdhQy_secret_AY0QHOox9y6WWeMA0Q07", "payment_method": "card", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } } }' ``` <img width="951" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/7ff612a4-a3d9-4b4f-8a50-bb26f75a4500"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
1adcf0150458c4670b81fa8e2307dc0c32aa1ff1
juspay/hyperswitch
juspay__hyperswitch-5211
Bug: pass fields to indicate if the customer address details to be connector from wallets Currently there are two fields which indicate if the customer address needs to be collected form the wallets like apple pay or google pay. And those fields are `collect_shipping_details_from_wallet_connector` and `collect_billing_details_from_wallet_connector`, and the same fields needs to be sent to sdk so that they can make the required decisions based on it.
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 0e2fd7b7039..c8826c02089 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -795,6 +795,12 @@ pub struct PaymentMethodListResponse { /// flag to indicate whether to perform external 3ds authentication #[schema(example = true)] pub request_external_three_ds_authentication: bool, + + /// flag that indicates whether to collect shipping details from wallets or from the customer + pub collect_shipping_details_from_wallets: Option<bool>, + + /// flag that indicates whether to collect billing details from wallets or from the customer + pub collect_billing_details_from_wallets: Option<bool>, } #[derive(Eq, PartialEq, Hash, Debug, serde::Deserialize, ToSchema)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index e58e16cc631..9180b8977ab 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2703,14 +2703,14 @@ pub async fn list_payment_methods( if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt .as_ref() .zip(payment_intent) - .zip(business_profile) + .zip(business_profile.as_ref()) .map(|((pa, pi), bp)| (pa, pi, bp)) { Box::pin(call_surcharge_decision_management( state, &merchant_account, &key_store, - &business_profile, + business_profile, payment_attempt, payment_intent, billing_address, @@ -2720,6 +2720,14 @@ pub async fn list_payment_methods( } else { api_surcharge_decision_configs::MerchantSurchargeConfigs::default() }; + + let collect_shipping_details_from_wallets = business_profile + .as_ref() + .and_then(|bp| bp.collect_shipping_details_from_wallet_connector); + + let collect_billing_details_from_wallets = business_profile + .as_ref() + .and_then(|bp| bp.collect_billing_details_from_wallet_connector); Ok(services::ApplicationResponse::Json( api::PaymentMethodListResponse { redirect_url: merchant_account.return_url, @@ -2756,6 +2764,8 @@ pub async fn list_payment_methods( .unwrap_or_default(), currency, request_external_three_ds_authentication, + collect_shipping_details_from_wallets, + collect_billing_details_from_wallets, }, )) } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 43900ac2b64..b52cf98b287 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -170,6 +170,7 @@ async fn create_applepay_session_token( connector.connector_name.to_string(), delayed_response, payment_types::NextActionCall::Confirm, + header_payload, ) } else { // Get the apple pay metadata @@ -345,8 +346,8 @@ async fn create_applepay_session_token( )?; let apple_pay_session_response = match ( - header_payload.browser_name, - header_payload.x_client_platform, + header_payload.browser_name.clone(), + header_payload.x_client_platform.clone(), ) { (Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web)) | (None, None) => { @@ -406,6 +407,7 @@ async fn create_applepay_session_token( connector.connector_name.to_string(), delayed_response, payment_types::NextActionCall::Confirm, + header_payload, ) } } @@ -489,6 +491,7 @@ fn create_apple_pay_session_response( connector_name: String, delayed_response: bool, next_action: payment_types::NextActionCall, + header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<types::PaymentsSessionRouterData> { match session_response { Some(response) => Ok(types::PaymentsSessionRouterData { @@ -508,23 +511,40 @@ fn create_apple_pay_session_response( }), ..router_data.clone() }), - None => Ok(types::PaymentsSessionRouterData { - response: Ok(types::PaymentsResponseData::SessionResponse { - session_token: payment_types::SessionToken::ApplePay(Box::new( - payment_types::ApplepaySessionTokenResponse { - session_token_data: None, - payment_request_data: apple_pay_payment_request, - connector: connector_name, - delayed_session_token: delayed_response, - sdk_next_action: { payment_types::SdkNextAction { next_action } }, - connector_reference_id: None, - connector_sdk_public_key: None, - connector_merchant_id: None, - }, - )), - }), - ..router_data.clone() - }), + None => { + match ( + header_payload.browser_name, + header_payload.x_client_platform, + ) { + ( + Some(common_enums::BrowserName::Safari), + Some(common_enums::ClientPlatform::Web), + ) + | (None, None) => Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::NoSessionTokenReceived, + }), + ..router_data.clone() + }), + _ => Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::ApplePay(Box::new( + payment_types::ApplepaySessionTokenResponse { + session_token_data: None, + payment_request_data: apple_pay_payment_request, + connector: connector_name, + delayed_session_token: delayed_response, + sdk_next_action: { payment_types::SdkNextAction { next_action } }, + connector_reference_id: None, + connector_sdk_public_key: None, + connector_merchant_id: None, + }, + )), + }), + ..router_data.clone() + }), + } + } } }
2024-07-04T12:17:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently there are two fields which indicate if the customer address needs to be collected form the wallets like apple pay or google pay. And those fields are `collect_shipping_details_from_wallet_connector` and `collect_billing_details_from_wallet_connector`, and the same fields needs to be sent to sdk so that they can make the required decisions based on it. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create stripe mca -> For the specific business profile set the below fields as ture ``` curl --location 'http://localhost:8080/account/merchant_1720165673/business_profile/pro_6Rcn7QpBhEJ1M76tiD4w' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: admin' \ --data '{ "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false }' ``` -> Create a payment with confirm false ``` { "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "aaa" } ``` -> Make session call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_05af5b5c33c54c33a8b11c3e77b99cc8' \ --data '{ "payment_id": "pay_xmrt6KKS0Vvye7OO1sIn", "wallets": [], "client_secret": "pay_xmrt6KKS0Vvye7OO1sIn_secret_8WAX2eYNDT4y5QfWrjL9" }' ``` Both shipping and billing will be false in the apple pay and google pay session token <img width="1183" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3db3ce79-de35-484b-9de2-a37b083e4d69"> -> Do merchant payment method list ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_xmrt6KKS0Vvye7OO1sIn_secret_8WAX2eYNDT4y5QfWrjL9' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_05af5b5c33c54c33a8b11c3e77b99cc8' ``` <img width="1172" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a917f21d-4eae-43aa-920c-1f059f77b5ab"> -> Now set the fields in the business profile with the below curl ``` curl --location 'http://localhost:8080/account/merchant_1720167317/business_profile/pro_VPeQOAs890a2r3IrsqCW' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_shipping_details_from_wallet_connector": true, "collect_billing_details_from_wallet_connector": true }' ``` <img width="1172" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d07bbc05-4af6-4bc3-92fe-1040b1b765bd"> -> Create a payment with confirm false -> Do a session call and the apple pay and the google pay should contain the billing and shipping fields <img width="1199" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/7486af2f-506c-4859-a051-0986f77a77ce"> -> Now make payment methods list <img width="1165" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9346efbc-47e4-4c54-a08a-e8278ffdb33b"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
755d968c95b8a5287408599de5187e50deac588f
juspay/hyperswitch
juspay__hyperswitch-5201
Bug: [Event Generation] KafkaTimestamp change from second to millisecond Kafka timestamp currently is in second * 1000 to convert to millisecond precision Issue with that is Kafka messages are getting out of order while pushing events as changes are happening in millisecond level Due to which re-ordering of messages is taking place and causing inconsistency in analytics and state of payment in sync sources
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index d1abda2105d..baa78339d91 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -319,11 +319,15 @@ impl KafkaProducer { BaseRecord::to(topic) .key(&event.key()) .payload(&event.value()?) - .timestamp( - event - .creation_timestamp() - .unwrap_or_else(|| OffsetDateTime::now_utc().unix_timestamp() * 1_000), - ), + .timestamp(event.creation_timestamp().unwrap_or_else(|| { + (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000) + .try_into() + .unwrap_or_else(|_| { + // kafka producer accepts milliseconds + // try converting nanos to millis if that fails convert seconds to millis + OffsetDateTime::now_utc().unix_timestamp() * 1_000 + }) + })), ) .map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}"))) .change_context(KafkaError::GenericError)
2024-07-04T09:33:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Adds millisecond timestamp to the kafka timestamp, would help in solving the re-ordering of events in kafka while pushing ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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. Issue link -> https://github.com/juspay/hyperswitch/issues/5201 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots) --> <img width="1486" alt="Screenshot 2024-07-04 at 3 02 32 PM" src="https://github.com/juspay/hyperswitch/assets/104988143/f25e41af-f74a-4acf-947d-ebe4a6895fe7"> <img width="1486" alt="Screenshot 2024-07-04 at 3 02 50 PM" src="https://github.com/juspay/hyperswitch/assets/104988143/4bc31792-f7d3-4d88-987b-34c7d628ea7e"> <img width="1472" alt="Screenshot 2024-07-04 at 3 07 25 PM" src="https://github.com/juspay/hyperswitch/assets/104988143/937cbcfa-7e49-4127-9ba8-f5a57b5e2f1a"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the cod - [ ] `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0796bb3b259c43f1105cf98e3d4407c46f4ca91d
juspay/hyperswitch
juspay__hyperswitch-5196
Bug: `override setup_future_usage` filed to on_session based on merchant config This is the use case where in which we need if the setup_future_usage is set to off_session in the payment method needs to be just saved at hyperswitch and not at connector. This feature is not working as expected during the pre-routing, hence needs to override it in the pre-routing as well. `skip_saving_wallet_at_connector_<merchant_id>` is the config which takes vector of payment method type as the value. When this config is set, the `setup_future_usage` is overridden to `on_session` by which mandates won't be created at the connector's end.
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f65cc052eaf..4af5a2ed308 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3279,7 +3279,7 @@ where && should_do_retry { let retryable_connector_data = helpers::get_apple_pay_retryable_connectors( - state, + &state, merchant_account, payment_data, key_store, @@ -3303,6 +3303,8 @@ where .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; + helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?; + return Ok(ConnectorCallType::PreDetermined( first_pre_routing_connector_data_list.clone(), )); @@ -3598,24 +3600,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone Ok(ConnectorCallType::PreDetermined(chosen_connector_data)) } _ => { - let skip_saving_wallet_at_connector_optional = - helpers::config_skip_saving_wallet_at_connector( - &*state.store, - &payment_data.payment_intent.merchant_id, - ) - .await?; - - if let Some(skip_saving_wallet_at_connector) = skip_saving_wallet_at_connector_optional - { - if let Some(payment_method_type) = payment_data.payment_attempt.payment_method_type - { - if skip_saving_wallet_at_connector.contains(&payment_method_type) { - logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate."); - payment_data.payment_intent.setup_future_usage = - Some(enums::FutureUsage::OnSession); - } - } - }; + helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?; let first_choice = connectors .first() diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 58f061115a1..0af7cebfd85 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -450,6 +450,7 @@ pub async fn get_token_pm_type_mandate_details( merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, payment_method_id: Option<String>, + customer_id: &Option<id_type::CustomerId>, ) -> RouterResult<MandateGenericData> { let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from); let ( @@ -553,7 +554,9 @@ pub async fn get_token_pm_type_mandate_details( || request.payment_method_type == Some(api_models::enums::PaymentMethodType::GooglePay) { - if let Some(customer_id) = &request.customer_id { + if let Some(customer_id) = + &request.customer_id.clone().or(customer_id.clone()) + { let customer_saved_pm_option = match state .store .find_payment_method_by_customer_id_merchant_id_list( @@ -4156,7 +4159,7 @@ pub fn get_applepay_metadata( #[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))] pub async fn get_apple_pay_retryable_connectors<F>( - state: SessionState, + state: &SessionState, merchant_account: &domain::MerchantAccount, payment_data: &mut PaymentData<F>, key_store: &domain::MerchantKeyStore, @@ -4180,7 +4183,7 @@ where .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; let merchant_connector_account_type = get_merchant_connector_account( - &state, + state, merchant_account.merchant_id.as_str(), payment_data.creds_identifier.to_owned(), key_store, @@ -4968,3 +4971,25 @@ pub async fn config_skip_saving_wallet_at_connector( } }) } + +pub async fn override_setup_future_usage_to_on_session<F: Clone>( + db: &dyn StorageInterface, + payment_data: &mut PaymentData<F>, +) -> CustomResult<(), errors::ApiErrorResponse> { + if payment_data.payment_intent.setup_future_usage == Some(enums::FutureUsage::OffSession) { + let skip_saving_wallet_at_connector_optional = + config_skip_saving_wallet_at_connector(db, &payment_data.payment_intent.merchant_id) + .await?; + + if let Some(skip_saving_wallet_at_connector) = skip_saving_wallet_at_connector_optional { + if let Some(payment_method_type) = payment_data.payment_attempt.payment_method_type { + if skip_saving_wallet_at_connector.contains(&payment_method_type) { + logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate."); + payment_data.payment_intent.setup_future_usage = + Some(enums::FutureUsage::OnSession); + } + } + }; + }; + Ok(()) +} diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 4fd427e38fa..7188a8216de 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -124,6 +124,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co merchant_account, key_store, payment_attempt.payment_method_id.clone(), + &payment_intent.customer_id, ) .await?; let token = token.or_else(|| payment_attempt.payment_token.clone()); diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 5e35b918a0f..99ac4e3e97c 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -495,6 +495,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let m_request = request.clone(); let m_key_store = key_store.clone(); + let payment_intent_customer_id = payment_intent.customer_id.clone(); + let mandate_details_fut = tokio::spawn( async move { helpers::get_token_pm_type_mandate_details( @@ -504,6 +506,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &m_merchant_account, &m_key_store, None, + &payment_intent_customer_id, ) .await } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index b8045487d9f..fc1f53d358d 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -136,6 +136,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa merchant_account, merchant_key_store, None, + &request.customer_id, ) .await?; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index c34a40fd908..c9b778fae31 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -148,6 +148,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa merchant_account, key_store, None, + &payment_intent.customer_id, ) .await?; helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?;
2024-07-03T18:05:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This is the use case where in which we need if the setup_future_usage is set to off_session in the payment method needs to be just saved at hyperswitch and not at connector. This is fix to override it during the pre-routing as well. `skip_saving_wallet_at_connector_<merchant_id>` is the config which takes vector of payment method type as the value. When this config is set, the `setup_future_usage` is overridden to `on_session` by which mandates won't be created at the connector's end. ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "skip_saving_wallet_at_connector_merchant_1718351667", "value": "[\"apple_pay\"]" }' ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant connector account -> Make a CIT with off_session and customer acceptance ``` { "amount": 800, "currency": "USD", "confirm": true, "amount_to_capture": 800, "customer_id": "{{$timestamp}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"\==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "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" } }, "connector_metadata": { "noon": { "order_category": "pay" } } } ``` <img width="1123" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/5ecd2a7a-6c4d-402f-b46d-8292f046bedc"> -> Create confirm false ``` { "amount": 2000, "currency": "USD", "confirm": false, "amount_to_capture": 2000, "customer_id": "1720081192", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "setup_future_usage": "off_session" } ``` <img width="1109" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4c3aff70-f371-4665-b901-610f10349aa9"> -> Confirm with payment data without customer acceptance ``` { "client_secret": "pay_Fgkr31SdjHPZJhq2ImD8_secret_SaWA7AtdvD467lCSnApQ", "payment_type": "new_mandate", "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` -> Now when listed the last used should be updated ``` curl --location 'http://localhost:8080/customers/1720081349/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: aaa' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f513c8e4daa95a6ceb89ce616e3d55058708fb2a
juspay/hyperswitch
juspay__hyperswitch-5188
Bug: [Analytics] - Refund status serialization issue for ckh analytics ```rust pub enum RefundStatus { Failure, ManualReview, #[default] Pending, Success, TransactionFailure, } ``` RefundStatus enum is serialized to snake_case but when the same event is pushed to kafka it is retained in camelCase. Due to this refund_status in clickhouse refunds table is in camelCase and ckh queries for analytics return 0 when refund_status = 'success' filter is applied
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 2ad0ad35cb3..fdf703dc026 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1547,6 +1547,7 @@ pub enum PaymentType { )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] pub enum RefundStatus { Failure, ManualReview,
2024-07-04T08:35:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> RefundStatus Enum does not support snake_case, so serde directive were added. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Run a Query : ``` {topic="hyperswitch-refund-events", source!="vector"} |= `ref_XPgVve1i7ISdDXfnxNy0` | json | line_format `{{.refund_status}}` ``` the Output should be : 2024-07-04 15:37:41.486 failure 2024-07-04 15:37:41.486 pending 2024-07-04 15:37:40.998 pending ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0796bb3b259c43f1105cf98e3d4407c46f4ca91d
juspay/hyperswitch
juspay__hyperswitch-5177
Bug: refactor(reports): Change permissions for report APIs Currently internal users are unable to use report APIs as some of them require Write permission which internal view only users doesn't have. We need to change the permission required to access report APIs.
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 6dde3eb888a..089e22a62a4 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -35,6 +35,7 @@ pub enum Permission { PayoutWrite, PayoutRead, WebhookEventWrite, + GenerateReport, } #[derive(Debug, serde::Serialize)] diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index cb34b8f6e93..3cde172d231 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -649,7 +649,7 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth(Permission::GenerateReport), api_locking::LockAction::NotApplicable, )) .await @@ -691,7 +691,7 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth(Permission::GenerateReport), api_locking::LockAction::NotApplicable, )) .await @@ -733,7 +733,7 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::PaymentWrite), + &auth::JWTAuth(Permission::GenerateReport), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index f3275a78fd0..c31e3d32b1f 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -19,14 +19,15 @@ pub fn get_permissions_vec(permission_group: &PermissionGroup) -> &[Permission] } } -pub static OPERATIONS_VIEW: [Permission; 7] = [ +pub static OPERATIONS_VIEW: [Permission; 8] = [ Permission::PaymentRead, Permission::RefundRead, Permission::MandateRead, Permission::DisputeRead, Permission::CustomerRead, - Permission::MerchantAccountRead, + Permission::GenerateReport, Permission::PayoutRead, + Permission::MerchantAccountRead, ]; pub static OPERATIONS_MANAGE: [Permission; 7] = [ @@ -35,8 +36,8 @@ pub static OPERATIONS_MANAGE: [Permission; 7] = [ Permission::MandateWrite, Permission::DisputeWrite, Permission::CustomerWrite, - Permission::MerchantAccountRead, Permission::PayoutWrite, + Permission::MerchantAccountRead, ]; pub static CONNECTORS_VIEW: [Permission; 2] = [ @@ -65,8 +66,11 @@ pub static WORKFLOWS_MANAGE: [Permission; 5] = [ Permission::MerchantAccountRead, ]; -pub static ANALYTICS_VIEW: [Permission; 2] = - [Permission::Analytics, Permission::MerchantAccountRead]; +pub static ANALYTICS_VIEW: [Permission; 3] = [ + Permission::Analytics, + Permission::GenerateReport, + Permission::MerchantAccountRead, +]; pub static USERS_VIEW: [Permission; 2] = [Permission::UsersRead, Permission::MerchantAccountRead]; diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 583b22fe86c..36ed89f4a44 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -34,6 +34,7 @@ pub enum Permission { WebhookEventWrite, PayoutRead, PayoutWrite, + GenerateReport, } impl Permission { @@ -75,6 +76,7 @@ impl Permission { Self::WebhookEventWrite => "Trigger retries for webhook events", Self::PayoutRead => "View all payouts", Self::PayoutWrite => "Create payout, download payout data", + Self::GenerateReport => "Generate reports for payments, refunds and disputes", } } } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index d0ad08848ca..b1fa4c3a178 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -47,6 +47,7 @@ impl From<Permission> for user_role_api::Permission { Permission::WebhookEventWrite => Self::WebhookEventWrite, Permission::PayoutRead => Self::PayoutRead, Permission::PayoutWrite => Self::PayoutWrite, + Permission::GenerateReport => Self::GenerateReport, } } }
2024-07-02T12:20:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently, internal users are unable to access payment generate report as it requires `PaymentWrite`. And other reports are having `Analytics` permission, but in the Front-end, the option is in Operations tab and in Analytics tab. Because Generate reports option is present in both Analytics and Operations, there will be a new permission, which will be available for both Operations and Analytics groups. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 #5177. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl 'http://localhost:8080/analytics/v1/report/payments' \ -H 'authorization: Bearer Internal user JWT' \ --data-raw '{"timeRange":{"startTime":"2024-07-01T11:34:38Z","endTime":"2024-07-02T11:34:38.441Z"},"dimensions":[]}' ``` When this API is hit by a internal user, this API should send email with report. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
dcc59115f2012d5544d6eb89f676c445a1392e13
juspay/hyperswitch
juspay__hyperswitch-5160
Bug: bug(auth_methods): Create auth methods is allowing auth methods with same type to be inserted multiple times Currently create will accept and insert auth methods with same type and name, which shouldn't be possible. Create should have checks for this and block these kind of requests.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 02a4a09dc94..66d4986129a 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -306,7 +306,9 @@ pub struct OpenIdConnectPublicConfig { pub name: OpenIdProvider, } -#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, strum::Display)] +#[derive( + Debug, serde::Deserialize, serde::Serialize, Copy, Clone, strum::Display, Eq, PartialEq, +)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OpenIdProvider { diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index ff1477aa3c9..952b74f5797 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2036,34 +2036,11 @@ pub async fn create_user_authentication_method( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; - let (private_config, public_config) = match req.auth_method { - user_api::AuthConfig::OpenIdConnect { - ref private_config, - ref public_config, - } => { - let private_config_value = serde_json::to_value(private_config.clone()) - .change_context(UserErrors::AuthConfigParsingError) - .attach_printable("Failed to convert auth config to json")?; - - let encrypted_config = domain::types::encrypt::<serde_json::Value, masking::WithType>( - private_config_value.into(), - &user_auth_encryption_key, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to encrypt auth config")?; - - Ok::<_, error_stack::Report<UserErrors>>(( - Some(encrypted_config.into()), - Some( - serde_json::to_value(public_config.clone()) - .change_context(UserErrors::AuthConfigParsingError) - .attach_printable("Failed to convert auth config to json")?, - ), - )) - } - _ => Ok((None, None)), - }?; + let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( + &req.auth_method, + &user_auth_encryption_key, + ) + .await?; let auth_methods = state .store @@ -2077,6 +2054,30 @@ pub async fn create_user_authentication_method( .map(|auth_method| auth_method.auth_id.clone()) .unwrap_or(uuid::Uuid::new_v4().to_string()); + for db_auth_method in auth_methods { + let is_type_same = db_auth_method.auth_type == (&req.auth_method).foreign_into(); + let is_extra_identifier_same = match &req.auth_method { + user_api::AuthConfig::OpenIdConnect { public_config, .. } => { + let db_auth_name = db_auth_method + .public_config + .map(|config| { + utils::user::parse_value::<user_api::OpenIdConnectPublicConfig>( + config, + "OpenIdConnectPublicConfig", + ) + }) + .transpose()? + .map(|config| config.name); + let req_auth_name = public_config.name; + db_auth_name.is_some_and(|name| name == req_auth_name) + } + user_api::AuthConfig::Password | user_api::AuthConfig::MagicLink => true, + }; + if is_type_same && is_extra_identifier_same { + return Err(report!(UserErrors::UserAuthMethodAlreadyExists)); + } + } + let now = common_utils::date_time::now(); state .store @@ -2085,7 +2086,7 @@ pub async fn create_user_authentication_method( auth_id, owner_id: req.owner_id, owner_type: req.owner_type, - auth_type: req.auth_method.foreign_into(), + auth_type: (&req.auth_method).foreign_into(), private_config, public_config, allow_signup: req.allow_signup, @@ -2114,34 +2115,11 @@ pub async fn update_user_authentication_method( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; - let (private_config, public_config) = match req.auth_method { - user_api::AuthConfig::OpenIdConnect { - ref private_config, - ref public_config, - } => { - let private_config_value = serde_json::to_value(private_config.clone()) - .change_context(UserErrors::AuthConfigParsingError) - .attach_printable("Failed to convert auth config to json")?; - - let encrypted_config = domain::types::encrypt::<serde_json::Value, masking::WithType>( - private_config_value.into(), - &user_auth_encryption_key, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to encrypt auth config")?; - - Ok::<_, error_stack::Report<UserErrors>>(( - Some(encrypted_config.into()), - Some( - serde_json::to_value(public_config.clone()) - .change_context(UserErrors::AuthConfigParsingError) - .attach_printable("Failed to convert auth config to json")?, - ), - )) - } - _ => Ok((None, None)), - }?; + let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( + &req.auth_method, + &user_auth_encryption_key, + ) + .await?; state .store @@ -2172,17 +2150,19 @@ pub async fn list_user_authentication_methods( .into_iter() .map(|auth_method| { let auth_name = match (auth_method.auth_type, auth_method.public_config) { - (common_enums::UserAuthType::OpenIdConnect, Some(config)) => { - let open_id_public_config = - serde_json::from_value::<user_api::OpenIdConnectPublicConfig>(config) - .change_context(UserErrors::InternalServerError) - .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; - - Ok(Some(open_id_public_config.name)) - } - (common_enums::UserAuthType::OpenIdConnect, None) => { - Err(UserErrors::InternalServerError) - .attach_printable("No config found for open_id_connect auth_method") + (common_enums::UserAuthType::OpenIdConnect, config) => { + let open_id_public_config: Option<user_api::OpenIdConnectPublicConfig> = + config + .map(|config| { + utils::user::parse_value(config, "OpenIdConnectPublicConfig") + }) + .transpose()?; + if let Some(public_config) = open_id_public_config { + Ok(Some(public_config.name)) + } else { + Err(report!(UserErrors::InternalServerError)) + .attach_printable("Public config not found for OIDC auth type") + } } _ => Ok(None), }?; diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index e80fe8d1de8..3cd35886ffe 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -207,9 +207,9 @@ pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnect .attach_printable("Failed to get redis connection") } -impl ForeignFrom<user_api::AuthConfig> for UserAuthType { - fn foreign_from(from: user_api::AuthConfig) -> Self { - match from { +impl ForeignFrom<&user_api::AuthConfig> for UserAuthType { + fn foreign_from(from: &user_api::AuthConfig) -> Self { + match *from { user_api::AuthConfig::OpenIdConnect { .. } => Self::OpenIdConnect, user_api::AuthConfig::Password => Self::Password, user_api::AuthConfig::MagicLink => Self::MagicLink, @@ -217,6 +217,49 @@ impl ForeignFrom<user_api::AuthConfig> for UserAuthType { } } +pub async fn construct_public_and_private_db_configs( + auth_config: &user_api::AuthConfig, + encryption_key: &[u8], +) -> UserResult<(Option<Encryption>, Option<serde_json::Value>)> { + match auth_config { + user_api::AuthConfig::OpenIdConnect { + private_config, + public_config, + } => { + let private_config_value = serde_json::to_value(private_config.clone()) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to convert auth config to json")?; + + let encrypted_config = domain::types::encrypt::<serde_json::Value, masking::WithType>( + private_config_value.into(), + encryption_key, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to encrypt auth config")?; + + Ok(( + Some(encrypted_config.into()), + Some( + serde_json::to_value(public_config.clone()) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to convert auth config to json")?, + ), + )) + } + user_api::AuthConfig::Password | user_api::AuthConfig::MagicLink => Ok((None, None)), + } +} + +pub fn parse_value<T>(value: serde_json::Value, type_name: &str) -> UserResult<T> +where + T: serde::de::DeserializeOwned, +{ + serde_json::from_value::<T>(value) + .change_context(UserErrors::InternalServerError) + .attach_printable(format!("Unable to parse {}", type_name)) +} + pub async fn decrypt_oidc_private_config( state: &SessionState, encrypted_config: Option<Encryption>,
2024-06-28T11:56:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently create will accept and insert auth methods with same type and name, which shouldn't be possible. This PR fixes that. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 #5160. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/user/auth' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "owner_id": "org_qaamgpukifSyBG0AxtYA2x", "owner_type": "organization", "auth_method": { "auth_type": "open_id_connect", "private_config": { "base_url": "https://dev-28418517.okta.com", "client_id": "0oahmmwdmuFvv2pFo5d7", "client_secret": "-VIrZZeN_A0SdSpFykAUZ0iMJNpSYQyILcfUmYlmZaLaFK7uRayrEuSvhs-Um5IR" }, "public_config": { "name": "okta" } }, "allow_signup": false }' ``` If this API is hit with same `auth_type` and `name` in `public_config`, then the API will throw the following error. ```json { "error": { "type": "invalid_request", "message": "User auth method already exists", "code": "UR_43" } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
af2497b5012f048a4cf72b61712812bca534c17c
juspay/hyperswitch
juspay__hyperswitch-5163
Bug: rename the browser name header to `x-browser-name` Rename the browser name header from `browsername` to `x-browser-name`
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index f0d332514d1..7059f0451ba 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -77,7 +77,7 @@ pub mod headers { pub const X_CLIENT_SOURCE: &str = "X-Client-Source"; pub const X_PAYMENT_CONFIRM_SOURCE: &str = "X-Payment-Confirm-Source"; pub const CONTENT_LENGTH: &str = "Content-Length"; - pub const BROWSER_NAME: &str = "browsername"; + pub const BROWSER_NAME: &str = "x-browser-name"; pub const X_CLIENT_PLATFORM: &str = "x-client-platform"; }
2024-06-28T13:46:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Rename the browser name header from `browsername` to `x-browser-name` Our web sdk is currently passing `browsername` also, but this will be removed going forward <img width="716" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e58c0601-0cba-4dfb-ab28-e21337227f2d"> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant connector account with apple pay manual flow. Below is the metadata for the manual flow. ``` "session_token_data": { "initiative": "web", "certificate": "==", "display_name": "applepay", "certificate_keys": "", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "", "payment_processing_certificate_key": "", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "", "merchant_business_country": "US" } ``` -> Session response when only `x-client-platform` is passed ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-client-platform: web' \ --header 'api-key: pk_dev_7e0d9f48e20b430baa86eb956dc99142' \ --data '{ "payment_id": "pay_7WAejcRN248R0Y7Kwsfh", "wallets": [], "client_secret": "pay_7WAejcRN248R0Y7Kwsfh_secret_CDL03LbGwQQnMPVA0Lq0" }' ``` <img width="903" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/b3a377eb-078b-4c3f-849d-2ebc8083a91c"> -> Session response when `x-client-platform` and `x-browser-name` are passed as `web` and `Safari` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Safari' \ --header 'x-client-platform: web' \ --header 'api-key: pk_dev_9754f74226e84eecbe72e09dc3890360' \ --data '{ "payment_id": "pay_aPyo8BbO9sjayVJ75O0B", "wallets": [], "client_secret": "pay_aPyo8BbO9sjayVJ75O0B_secret_IHwD3t4hMolns4eIKIep" }' ``` <img width="1112" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/6b298647-95c1-496e-b75b-135dcc9e86f0"> -> When only is `x-client-platform: ios` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-client-platform: ios' \ --header 'api-key: pk_dev_30a379e8af2d46f6be977b01d8b38708' \ --data '{ "payment_id": "pay_CGA1yXcMIArRqgn9ZyuD", "wallets": [], "client_secret": "pay_CGA1yXcMIArRqgn9ZyuD_secret_A2MRtOhcSzFGhEeEukRv" }' ``` <img width="956" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f36d61b5-8c59-4526-818f-f834262cbccf"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
910fcc89e24b8accd59a5a30021837222f803fa9
juspay/hyperswitch
juspay__hyperswitch-5198
Bug: [FEATURE]: Add support for merchant order reference id ### Feature Description Add support for merchant order reference id ### Possible Implementation Add support for merchant order reference id ### 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 d8321524a1e..673a5cdae4f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -506,6 +506,16 @@ pub struct PaymentsRequest { /// Fee information to be charged on the payment being collected pub charges: Option<PaymentChargeRequest>, + + /// Merchant's identifier for the payment/invoice. This will be sent to the connector + /// if the connector provides support to accept multiple reference ids. + /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. + #[schema( + value_type = Option<String>, + max_length = 255, + example = "Custom_Order_id_123" + )] + pub merchant_order_reference_id: Option<String>, } /// Fee information to be charged on the payment being collected @@ -3623,6 +3633,16 @@ pub struct PaymentsResponse { /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, + + /// Merchant's identifier for the payment/invoice. This will be sent to the connector + /// if the connector provides support to accept multiple reference ids. + /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. + #[schema( + value_type = Option<String>, + max_length = 255, + example = "Custom_Order_id_123" + )] + pub merchant_order_reference_id: Option<String>, } /// Fee information to be charged on the payment being collected diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index fa37eecdbfe..bc480c497ea 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -60,6 +60,7 @@ pub struct PaymentIntent { pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, + pub merchant_order_reference_id: Option<String>, } #[derive( @@ -116,6 +117,7 @@ pub struct PaymentIntentNew { pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, + pub merchant_order_reference_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -175,6 +177,7 @@ pub enum PaymentIntentUpdate { request_external_three_ds_authentication: Option<bool>, frm_metadata: Option<pii::SecretSerdeValue>, customer_details: Option<Encryption>, + merchant_order_reference_id: Option<String>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, @@ -251,6 +254,7 @@ pub struct PaymentIntentUpdateInternal { pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, + pub merchant_order_reference_id: Option<String>, } impl PaymentIntentUpdate { @@ -287,6 +291,7 @@ impl PaymentIntentUpdate { request_external_three_ds_authentication, frm_metadata, customer_details, + merchant_order_reference_id, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), @@ -325,6 +330,8 @@ impl PaymentIntentUpdate { .or(source.request_external_three_ds_authentication), frm_metadata: frm_metadata.or(source.frm_metadata), customer_details: customer_details.or(source.customer_details), + merchant_order_reference_id: merchant_order_reference_id + .or(source.merchant_order_reference_id), ..source } } @@ -356,6 +363,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { request_external_three_ds_authentication, frm_metadata, customer_details, + merchant_order_reference_id, } => Self { amount: Some(amount), currency: Some(currency), @@ -380,6 +388,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { request_external_three_ds_authentication, frm_metadata, customer_details, + merchant_order_reference_id, ..Default::default() }, PaymentIntentUpdate::MetadataUpdate { diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 98f1b2fbbec..0b00e57a1c8 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -890,6 +890,8 @@ diesel::table! { charges -> Nullable<Jsonb>, frm_metadata -> Nullable<Jsonb>, customer_details -> Nullable<Bytea>, + #[max_length = 255] + merchant_order_reference_id -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index f6e4f888790..0c22c70bc36 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -63,4 +63,5 @@ pub struct PaymentIntent { pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, + pub merchant_order_reference_id: Option<String>, } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 1dca50e6482..01737076615 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -530,6 +530,7 @@ impl behaviour::Conversion for PaymentIntent { charges: self.charges, frm_metadata: self.frm_metadata, customer_details: self.customer_details.map(Encryption::from), + merchant_order_reference_id: self.merchant_order_reference_id, }) } @@ -591,6 +592,7 @@ impl behaviour::Conversion for PaymentIntent { .customer_details .async_lift(inner_decrypt) .await?, + merchant_order_reference_id: storage_model.merchant_order_reference_id, }) } .await @@ -645,6 +647,7 @@ impl behaviour::Conversion for PaymentIntent { charges: self.charges, frm_metadata: self.frm_metadata, customer_details: self.customer_details.map(Encryption::from), + merchant_order_reference_id: self.merchant_order_reference_id, }) } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 30fd1061c7f..fb824a80798 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -193,6 +193,7 @@ pub enum PaymentIntentUpdate { session_expiry: Option<PrimitiveDateTime>, request_external_three_ds_authentication: Option<bool>, customer_details: Option<Encryptable<Secret<serde_json::Value>>>, + merchant_order_reference_id: Option<String>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, @@ -270,6 +271,7 @@ pub struct PaymentIntentUpdateInternal { pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, + pub merchant_order_reference_id: Option<String>, } impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { @@ -298,6 +300,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { request_external_three_ds_authentication, frm_metadata, customer_details, + merchant_order_reference_id, } => Self { amount: Some(amount), currency: Some(currency), @@ -322,6 +325,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { request_external_three_ds_authentication, frm_metadata, customer_details, + merchant_order_reference_id, ..Default::default() }, PaymentIntentUpdate::MetadataUpdate { @@ -562,6 +566,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { request_external_three_ds_authentication, frm_metadata, customer_details, + merchant_order_reference_id, } => Self::Update { amount, currency, @@ -585,6 +590,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { request_external_three_ds_authentication, frm_metadata, customer_details: customer_details.map(Encryption::from), + merchant_order_reference_id, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, @@ -687,6 +693,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt request_external_three_ds_authentication, frm_metadata, customer_details, + merchant_order_reference_id, } = value; Self { @@ -721,6 +728,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt request_external_three_ds_authentication, frm_metadata, customer_details: customer_details.map(Encryption::from), + merchant_order_reference_id, } } } diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 8496827ff25..6d7e42eb1ae 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -62,6 +62,11 @@ pub struct PaymentsAuthorizeData { // New amount for amount frame work pub minor_amount: MinorUnit, + + /// Merchant's identifier for the payment/invoice. This will be sent to the connector + /// if the connector provides support to accept multiple reference ids. + /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. + pub merchant_order_reference_id: Option<String>, pub integrity_object: Option<AuthoriseIntegrityObject>, } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 9778d6d33a4..9a85522396d 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -179,6 +179,7 @@ pub struct AdyenPaymentRequest<'a> { line_items: Option<Vec<LineItem>>, channel: Option<Channel>, metadata: Option<pii::SecretSerdeValue>, + merchant_order_reference: Option<String>, } #[derive(Debug, Serialize)] @@ -2610,6 +2611,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } } @@ -2672,6 +2674,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } } @@ -2725,6 +2728,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }; Ok(request) } @@ -2779,6 +2783,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }; Ok(request) } @@ -2829,6 +2834,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }; Ok(request) } @@ -2879,6 +2885,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }; Ok(request) } @@ -2939,6 +2946,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } } @@ -3034,6 +3042,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } } @@ -3109,6 +3118,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } } @@ -3167,6 +3177,7 @@ impl<'a> shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), metadata: item.router_data.request.metadata.clone(), + merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } } diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index ab3463e3671..e6f0bab9c2c 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -78,6 +78,7 @@ pub struct KlarnaPaymentsRequest { purchase_country: enums::CountryAlpha2, purchase_currency: enums::Currency, merchant_reference1: Option<String>, + merchant_reference2: Option<String>, shipping_address: Option<KlarnaShippingAddress>, } @@ -213,6 +214,7 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaP }) .collect(), merchant_reference1: Some(item.router_data.connector_request_reference_id.clone()), + merchant_reference2: item.router_data.request.merchant_order_reference_id.clone(), auto_capture: request.is_auto_capture()?, shipping_address: get_address_info(item.router_data.get_optional_shipping()) .transpose()?, diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 39ea808d61f..7ec6b1c4af6 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -397,7 +397,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP let purchase_units = vec![PurchaseUnitRequest { reference_id: Some(connector_request_reference_id.clone()), - custom_id: Some(connector_request_reference_id.clone()), + custom_id: item.router_data.request.merchant_order_reference_id.clone(), invoice_id: Some(connector_request_reference_id), amount, payee, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 534da72a1d9..650ac1786ae 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3133,6 +3133,7 @@ mod tests { charges: None, frm_metadata: None, customer_details: None, + merchant_order_reference_id: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok()); @@ -3193,6 +3194,7 @@ mod tests { charges: None, frm_metadata: None, customer_details: None, + merchant_order_reference_id: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err()) @@ -3252,6 +3254,7 @@ mod tests { charges: None, frm_metadata: None, customer_details: None, + merchant_order_reference_id: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err()) diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 5e35b918a0f..e140a8e02df 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1259,6 +1259,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen request_external_three_ds_authentication: None, frm_metadata: m_frm_metadata, customer_details, + merchant_order_reference_id: None, }, &m_key_store, storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index b8045487d9f..2414db55997 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1116,6 +1116,7 @@ impl PaymentCreate { charges, frm_metadata: request.frm_metadata.clone(), customer_details, + merchant_order_reference_id: request.merchant_order_reference_id.clone(), }) } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index c34a40fd908..ca069c8bf6c 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -371,6 +371,11 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .request_external_three_ds_authentication .or(payment_intent.request_external_three_ds_authentication); + payment_intent.merchant_order_reference_id = request + .merchant_order_reference_id + .clone() + .or(payment_intent.merchant_order_reference_id); + Self::populate_payment_attempt_with_request(&mut payment_attempt, request); let creds_identifier = request @@ -706,6 +711,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let metadata = payment_data.payment_intent.metadata.clone(); let frm_metadata = payment_data.payment_intent.frm_metadata.clone(); let session_expiry = payment_data.payment_intent.session_expiry; + let merchant_order_reference_id = payment_data + .payment_intent + .merchant_order_reference_id + .clone(); + payment_data.payment_intent = state .store .update_payment_intent( @@ -735,6 +745,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .request_external_three_ds_authentication, frm_metadata, customer_details, + merchant_order_reference_id, }, key_store, storage_scheme, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index abcb4859710..aaf8e3b3a07 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -880,6 +880,7 @@ where .set_updated(Some(payment_intent.modified_at)) .set_charges(charges_response) .set_frm_metadata(payment_intent.frm_metadata) + .set_merchant_order_reference_id(payment_intent.merchant_order_reference_id) .to_owned(), headers, )) @@ -1305,6 +1306,11 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz None => None, }; + let merchant_order_reference_id = payment_data + .payment_intent + .merchant_order_reference_id + .clone(); + Ok(Self { payment_method_data: From::from( payment_method_data.get_required_value("payment_method_data")?, @@ -1350,6 +1356,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .transpose()?, customer_acceptance: payment_data.customer_acceptance, charges, + merchant_order_reference_id, integrity_object: None, }) } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index e6381e84b15..c457ca59df8 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -789,6 +789,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData { authentication_data: None, customer_acceptance: data.request.customer_acceptance.clone(), charges: None, // TODO: allow charges on mandates? + merchant_order_reference_id: None, integrity_object: None, } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 60b40e78663..859f02d8fcc 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -55,6 +55,7 @@ impl VerifyConnectorData { authentication_data: None, customer_acceptance: None, charges: None, + merchant_order_reference_id: None, integrity_object: None, } } diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 97c063eb3ae..28976236df9 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -226,6 +226,7 @@ pub async fn generate_sample_data( charges: None, frm_metadata: Default::default(), customer_details: None, + merchant_order_reference_id: Default::default(), }; let payment_attempt = PaymentAttemptBatchNew { attempt_id: attempt_id.clone(), diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 53bbea865c2..153134964be 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -937,6 +937,7 @@ impl Default for PaymentAuthorizeType { customer_acceptance: None, charges: None, integrity_object: None, + merchant_order_reference_id: None, }; Self(data) } diff --git a/migrations/2024-07-03-182616_add_merchant_order_reference_id/down.sql b/migrations/2024-07-03-182616_add_merchant_order_reference_id/down.sql new file mode 100644 index 00000000000..bcfedcf6b4e --- /dev/null +++ b/migrations/2024-07-03-182616_add_merchant_order_reference_id/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent DROP COLUMN IF EXISTS merchant_order_reference_id; \ No newline at end of file diff --git a/migrations/2024-07-03-182616_add_merchant_order_reference_id/up.sql b/migrations/2024-07-03-182616_add_merchant_order_reference_id/up.sql new file mode 100644 index 00000000000..cd5d2359c59 --- /dev/null +++ b/migrations/2024-07-03-182616_add_merchant_order_reference_id/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS merchant_order_reference_id VARCHAR(255) DEFAULT NULL; \ No newline at end of file
2024-07-03T19:49:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add support for accepting `merchant_order_reference_id` and subsequently pass it to the connector if connector supports accepting multiple reference. This is being added for merchant to locate the payment using their id in the connector dashboard ### Additional Changes - [X] This PR modifies the API contract - [X] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> #5198 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### Do Payments Create and Update the `merchant_order_reference_id`, check this in DB ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_JBNIuXN6ZUGXy4t5xk3btwzLBSxNJTfZHL6sYilDuqYUgMZulcithuwgj0UAYwCc' \ --data-raw '{ "amount": 6100, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6100, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } }, "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" } }, "merchant_order_reference_id": "cust_order_id" }' ``` ``` curl --location 'http://localhost:8080/payments/pay_BCFeb1tpuJWad7PElBM1' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_JBNIuXN6ZUGXy4t5xk3btwzLBSxNJTfZHL6sYilDuqYUgMZulcithuwgj0UAYwCc' \ --data '{ "amount": 6540, "confirm" :false, "amount_to_capture": 6540, "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } } , "merchant_order_reference_id": "true" }' ``` ### Create Paypal Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_JBNIuXN6ZUGXy4t5xk3btwzLBSxNJTfZHL6sYilDuqYUgMZulcithuwgj0UAYwCc' \ --data-raw '{ "amount": 6100, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 6100, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } }, "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" } }, "merchant_order_reference_id": "cust_order_id" }' ``` <img width="1441" alt="Screenshot 2024-07-04 at 2 57 04 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/5213f556-a1c4-4d68-981f-5f2b559daca9"> ### Create Adyen Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_tRtH96ICztwLahErT89hnUwUjGNvNUSA6zZqpedyIruXledDUHfp5o0yQLRNCPB8' \ --header 'x-feature: router-custom' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 1337, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1337, "customer_id": "customerg12", "email": "customer@email.se", "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": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111145551142", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1", "line2": "Stargatan", "city": "Stockholm", "zip": "11 148", "country": "SE", "first_name": "Alice", "last_name": "Test" } }, "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" } }, "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" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "test": "ket" }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ], "merchant_order_reference_id": "cust_order_adyen" }' ``` <img width="593" alt="Screenshot 2024-07-04 at 3 08 44 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/59036dcd-08bc-4618-a0c7-f666367a1a34"> ### Create klarna Payment ``` Add merchant_order_reference_id in the request field from SDK ``` ![image](https://github.com/juspay/hyperswitch/assets/55536657/6cc800b4-3c8a-4ed4-b6d7-6e156b485664) ### Test webhooks for Adyen and Paypal ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c8c0cb765e8a511aae0b3a4f94115bb07d122c9d
juspay/hyperswitch
juspay__hyperswitch-5189
Bug: Add appropriate missing logs for payment methods Add missing logs for payment methods flow (both merchant and customer).
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 41007286b83..1523ac18cb5 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2002,6 +2002,8 @@ pub async fn list_payment_methods( cust_pm.payment_method_type == Some(mca.payment_method_type) })) }); + + logger::debug!("Filtered out wallet payment method from mca since customer has already saved it"); Ok(()) } Err(error) => { @@ -3872,6 +3874,9 @@ pub async fn get_card_details_with_locker_fallback( None } } else { + logger::debug!( + "Getting card details from locker as it is not found in payment methods table" + ); Some(get_card_details_from_locker(state, pm).await?) }) } @@ -3899,6 +3904,9 @@ pub async fn get_card_details_without_locker_fallback( crd.scheme.clone_from(&pm.scheme); crd } else { + logger::debug!( + "Getting card details from locker as it is not found in payment methods table" + ); get_card_details_from_locker(state, pm).await? }) }
2024-07-03T09:57:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds missing logs for payment methods flow (both merchant and customer). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This PR only adds logs so basic sanity tests should suffice ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f3fb59ce7448f91b74d0be4a75d82e282f075a66
juspay/hyperswitch
juspay__hyperswitch-5158
Bug: fix: print x request id for user postman tests Console log x request id for users postman tests, - it will help to debug failed tests for user collection
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js index 16fca64a141..a9297538452 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status 4xx pm.test("[POST]::/user/v2/signin?token_only=true - Status code is 401", function () { pm.response.to.have.status(401); diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js index a8b3658e5ff..9105ce122cb 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status 2xx pm.test("[POST]::user/v2/signin?token_only=true - Status code is 2xx", function () { pm.response.to.be.success; diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js index e0149290da6..6cb6b69ba6c 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status code is 4xx Bad Request pm.test("[POST]::/user/v2/signin - Status code is 401", function () { pm.response.to.have.status(401); diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js index 174cbd8e5e2..4724ff5981f 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status 2xx pm.test("[POST]::/user/v2/signin - Status code is 2xx", function () { pm.response.to.be.success; diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js index 6dbed06b0f6..0c6426d4cfe 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status 2xx pm.test("[POST]::/user/connect_account - Status code is 2xx", function () { pm.response.to.be.success; @@ -21,3 +23,4 @@ pm.test("[POST]::/user/connect_account - Response contains is_email_sent", funct pm.expect(jsonData).to.have.property("is_email_sent"); pm.expect(jsonData.is_email_sent).to.be.true; }); + diff --git a/postman/collection-json/users.postman_collection.json b/postman/collection-json/users.postman_collection.json index 943d37d22d3..d6067fd668c 100644 --- a/postman/collection-json/users.postman_collection.json +++ b/postman/collection-json/users.postman_collection.json @@ -1,556 +1,567 @@ { - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - } - ], - "item": [ - { - "name": "Health check", - "item": [ - { - "name": "New Request", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/health - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "{{baseUrl}}/health", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "health" - ] - } - }, - "response": [] - } - ] - }, - { - "name": "Flow Testcases", - "item": [ - { - "name": "Sign Up", - "item": [ - { - "name": "Connect Account", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/user/connect_account - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/user/connect_account - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Validate specific JSON response content", - "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {", - " var jsonData = pm.response.json();", - " pm.expect(jsonData).to.have.property(\"is_email_sent\");", - " pm.expect(jsonData.is_email_sent).to.be.true;", - "});", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "", - "var baseEmail = pm.environment.get('user_base_email_for_signup');", - "var emailDomain = pm.environment.get(\"user_domain_for_signup\");", - "", - "// Generate a unique email address", - "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;", - "// Set the unique email address as an environment variable", - "pm.environment.set('unique_email', uniqueEmail);", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{unique_email}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/connect_account", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "connect_account" - ] - } - }, - "response": [] - } - ] - }, - { - "name": "Sign In", - "item": [ - { - "name": "Signin", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Validate specific JSON response content", - "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {", - " var jsonData = pm.response.json();", - " pm.expect(jsonData).to.have.property(\"token\");", - " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", - "});" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/v2/signin", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "v2", - "signin" - ] - } - }, - "response": [] - }, - { - "name": "Signin Wrong", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status code is 4xx Bad Request", - "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {", - " pm.response.to.have.status(401);", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/v2/signin", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "v2", - "signin" - ] - } - }, - "response": [] - }, - { - "name": "Signin Token Only", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Validate specific JSON response content", - "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {", - " var jsonData = pm.response.json();", - " pm.expect(jsonData).to.have.property(\"token\");", - " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/v2/signin?token_only=true", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "v2", - "signin" - ], - "query": [ - { - "key": "token_only", - "value": "true" - } - ] - } - }, - "response": [] - }, - { - "name": "Signin Token Only Wrong", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 4xx", - "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {", - " pm.response.to.have.status(401);", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/v2/signin?token_only=true", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "v2", - "signin" - ], - "query": [ - { - "key": "token_only", - "value": "true" - } - ] - } - }, - "response": [] - } - ] - } - ] - } - ], - "info": { - "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9", - "name": "users", - "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", - "_exporter_id": "26710321" - }, - "variable": [ - { - "key": "baseUrl", - "value": "", - "type": "string" - }, - { - "key": "admin_api_key", - "value": "", - "type": "string" - }, - { - "key": "api_key", - "value": "", - "type": "string" - }, - { - "key": "merchant_id", - "value": "" - }, - { - "key": "payment_id", - "value": "" - }, - { - "key": "customer_id", - "value": "" - }, - { - "key": "mandate_id", - "value": "" - }, - { - "key": "payment_method_id", - "value": "" - }, - { - "key": "refund_id", - "value": "" - }, - { - "key": "merchant_connector_id", - "value": "" - }, - { - "key": "client_secret", - "value": "", - "type": "string" - }, - { - "key": "connector_api_key", - "value": "", - "type": "string" - }, - { - "key": "publishable_key", - "value": "", - "type": "string" - }, - { - "key": "api_key_id", - "value": "", - "type": "string" - }, - { - "key": "payment_token", - "value": "" - }, - { - "key": "gateway_merchant_id", - "value": "", - "type": "string" - }, - { - "key": "certificate", - "value": "", - "type": "string" - }, - { - "key": "certificate_keys", - "value": "", - "type": "string" - }, - { - "key": "connector_api_secret", - "value": "", - "type": "string" - }, - { - "key": "connector_key1", - "value": "", - "type": "string" - }, - { - "key": "connector_key2", - "value": "", - "type": "string" - }, - { - "key": "user_email", - "value": "", - "type": "string" - }, - { - "key": "user_password", - "value": "", - "type": "string" - }, - { - "key": "wrong_password", - "value": "", - "type": "string" - }, - { - "key": "user_base_email_for_signup", - "value": "", - "type": "string" - }, - { - "key": "user_domain_for_signup", - "value": "", - "type": "string" - } - ] -} + "info": { + "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9", + "name": "users", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "26710321" + }, + "item": [ + { + "name": "Health check", + "item": [ + { + "name": "New Request", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/health - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "health" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Flow Testcases", + "item": [ + { + "name": "Sign Up", + "item": [ + { + "name": "Connect Account", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/connect_account - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/user/connect_account - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"is_email_sent\");", + " pm.expect(jsonData.is_email_sent).to.be.true;", + "});", + "", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "", + "var baseEmail = pm.environment.get('user_base_email_for_signup');", + "var emailDomain = pm.environment.get(\"user_domain_for_signup\");", + "", + "// Generate a unique email address", + "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;", + "// Set the unique email address as an environment variable", + "pm.environment.set('unique_email', uniqueEmail);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{unique_email}}\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/user/connect_account", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "connect_account" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Sign In", + "item": [ + { + "name": "Signin", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"token\");", + " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{user_password}}\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } + }, + "response": [] + }, + { + "name": "Signin Wrong", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status code is 4xx Bad Request", + "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{wrong_password}}\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } + }, + "response": [] + }, + { + "name": "Signin Token Only", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"token\");", + " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{user_password}}\" \n}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } + }, + "response": [] + }, + { + "name": "Signin Token Only Wrong", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status 4xx", + "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{wrong_password}}\" \n}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } + }, + "response": [] + } + ] + } + ] + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "key": "baseUrl", + "value": "", + "type": "string" + }, + { + "key": "admin_api_key", + "value": "", + "type": "string" + }, + { + "key": "api_key", + "value": "", + "type": "string" + }, + { + "key": "merchant_id", + "value": "" + }, + { + "key": "payment_id", + "value": "" + }, + { + "key": "customer_id", + "value": "" + }, + { + "key": "mandate_id", + "value": "" + }, + { + "key": "payment_method_id", + "value": "" + }, + { + "key": "refund_id", + "value": "" + }, + { + "key": "merchant_connector_id", + "value": "" + }, + { + "key": "client_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_api_key", + "value": "", + "type": "string" + }, + { + "key": "publishable_key", + "value": "", + "type": "string" + }, + { + "key": "api_key_id", + "value": "", + "type": "string" + }, + { + "key": "payment_token", + "value": "" + }, + { + "key": "gateway_merchant_id", + "value": "", + "type": "string" + }, + { + "key": "certificate", + "value": "", + "type": "string" + }, + { + "key": "certificate_keys", + "value": "", + "type": "string" + }, + { + "key": "connector_api_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_key1", + "value": "", + "type": "string" + }, + { + "key": "connector_key2", + "value": "", + "type": "string" + }, + { + "key": "user_email", + "value": "", + "type": "string" + }, + { + "key": "user_password", + "value": "", + "type": "string" + }, + { + "key": "wrong_password", + "value": "", + "type": "string" + }, + { + "key": "user_base_email_for_signup", + "value": "", + "type": "string" + }, + { + "key": "user_domain_for_signup", + "value": "", + "type": "string" + } + ] +} \ No newline at end of file
2024-06-28T10:38:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description For user postman tests log x request id for every request. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes #5158 ## How did you test it? Use command ``` cargo run --bin test_utils -- --module-name="users" --base-url="http://localhost:8080" --admin-api-key="admin_api_key" ``` Results will contain x request id for every request: ![image](https://github.com/juspay/hyperswitch/assets/64925866/5ffc977c-2d63-40d3-bb71-48adfe5687a7) Local Response in Postman Collection: <img width="1728" alt="Screenshot 2024-06-28 at 4 25 19 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/74b38d70-2fb9-439c-8353-71a285277c21"> <img width="1258" alt="Screenshot 2024-06-28 at 4 25 35 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/36a439f1-b0f3-4961-9508-08bef068b623"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d2626fa3fe4216504fd0df216eea8462c87cce07
juspay/hyperswitch
juspay__hyperswitch-5175
Bug: Adding Contributors Guide to the Readme of the repository Being an open source project, we look forward to contributors from across the world. For that we have outlined few changes which will make it easier for contributors to navigate through the project with more ease, and quickly develop a better understanding of the working of different components of Hyperswitch.
diff --git a/README.md b/README.md index e8dd2f31674..ccdd6e19b6d 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,6 @@ Here are the components of Hyperswitch that deliver the whole solution: Jump in and contribute to these repositories to help improve and expand Hyperswitch! <br> -<img src="./docs/imgs/hyperswitch-product.png" alt="Hyperswitch-Product" width="50%"/> <a href="#Quick Setup"> <h2 id="quick-setup">⚡️ Quick Setup</h2>
2024-10-18T11:42:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Closes - #5175 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
451376e7993839f5c93624c12833af7d47aa4e34
juspay/hyperswitch
juspay__hyperswitch-5174
Bug: Updating the API reference documentation - payments We have had feedback related to the API doc being outdated, and lacking proper visibility of the latest spec of the API collection.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index cd36c53a12b..2dc51a3783b 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -251,12 +251,12 @@ pub struct PaymentsRequest { #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, - /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. + /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments - /// that have been done by a single merchant. This field is auto generated and is returned in the API response. + /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, @@ -272,13 +272,14 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<String>, + /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, - /// This allows to manually select a connector with which the payment can go through + /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, @@ -298,7 +299,7 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, - /// Whether to confirm the payment (if applicable) + /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, @@ -341,7 +342,7 @@ pub struct PaymentsRequest { #[schema(example = "It's my first payment request")] pub description: Option<String>, - /// The URL to redirect after the completion of the operation + /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, @@ -355,7 +356,7 @@ pub struct PaymentsRequest { #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, - /// Provide a reference to a stored payment method + /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, @@ -392,7 +393,7 @@ pub struct PaymentsRequest { /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, - /// We will be Passing this "CustomerAcceptance" object during Payments-Confirm. The customer_acceptance sub object is usually passed by the SDK or client + /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, @@ -462,18 +463,17 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, - /// Whether to get the payment link (if applicable) + /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, - /// custom payment link config id set at business profile send only if business_specific_configs is configured + /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, - /// The business profile to use for this payment, if not passed the default business profile - /// associated with the merchant account will be used. + /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub profile_id: Option<String>, @@ -485,7 +485,7 @@ pub struct PaymentsRequest { #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, - ///Request for an incremental authorization + ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds @@ -493,7 +493,7 @@ pub struct PaymentsRequest { #[schema(example = 900)] pub session_expiry: Option<u32>, - /// additional data related to some frm(Fraud Risk Management) connectors + /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, @@ -535,7 +535,7 @@ impl PaymentsRequest { } } -/// details of surcharge applied on this payment, if applicable +/// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] @@ -629,7 +629,7 @@ pub struct PaymentAttemptResponse { pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, - /// If there was an error while calling the connector the error message is received here + /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] @@ -642,15 +642,15 @@ pub struct PaymentAttemptResponse { /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, - /// If the payment was cancelled the reason provided here + /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, - /// If there was an error while calling the connectors the code is received here + /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, - /// additional data related to some connectors + /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] @@ -658,12 +658,12 @@ pub struct PaymentAttemptResponse { /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, - /// reference to the payment at connector side + /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, - /// error code unified across the connectors is received here if there was an error while calling connector + /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, - /// error message unified across the connectors is received here if there was an error while calling connector + /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, @@ -675,7 +675,7 @@ pub struct PaymentAttemptResponse { Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { - /// unique identifier for the capture + /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] @@ -688,11 +688,11 @@ pub struct CaptureResponse { pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, - /// unique identifier for the parent attempt on which this capture is made + /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, - /// A unique identifier for a capture provided by the connector + /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, - /// sequence number of this capture + /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, @@ -700,7 +700,7 @@ pub struct CaptureResponse { pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, - /// reference to the capture at connector side + /// Reference to the capture at connector side pub reference_id: Option<String>, } @@ -854,6 +854,7 @@ impl MandateIds { } } +/// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] @@ -911,7 +912,7 @@ impl Default for MandateType { } } -/// We will be Passing this "CustomerAcceptance" object during Payments-Confirm. The customer_acceptance sub object is usually passed by the SDK or client +/// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { @@ -3383,7 +3384,7 @@ pub struct PaymentsResponse { #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, - /// List of dispute that happened on this intent + /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, @@ -3486,7 +3487,7 @@ pub struct PaymentsResponse { /// Additional information required for redirection pub next_action: Option<NextActionData>, - /// If the payment was cancelled the reason provided here + /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here @@ -3548,11 +3549,11 @@ pub struct PaymentsResponse { #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, - /// additional data related to some connectors + /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated - /// additional data that might be required by hyperswitch + /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated @@ -3565,10 +3566,10 @@ pub struct PaymentsResponse { /// The business profile that is associated with this payment pub profile_id: Option<String>, - /// details of surcharge applied on this payment + /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, - /// total number of attempts associated with this payment + /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment @@ -3605,10 +3606,10 @@ pub struct PaymentsResponse { /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, - /// Identifier for Payment Method + /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, - /// Payment Method Status + /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, @@ -4250,7 +4251,7 @@ pub struct ApplepaySessionRequest { pub initiative_context: String, } -/// additional data related to some connectors +/// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, @@ -5127,7 +5128,7 @@ pub struct PaymentLinkListResponse { pub data: Vec<PaymentLinkResponse>, } -/// custom payment link config for the particular payment +/// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 2ad0ad35cb3..e6ab3435252 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1203,7 +1203,7 @@ pub enum IntentStatus { PartiallyCapturedAndCapturable, } -/// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. +/// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[derive( Clone, Copy, @@ -1506,7 +1506,7 @@ pub enum PaymentMethod { GiftCard, } -/// To be used to specify the type of payment. Use 'setup_mandate' in case of zero auth flow. +/// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index 66e6ce42962..653fa16c75e 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -1,10 +1,12 @@ /// Payments - Create /// -/// **Creates a payment object when amount and currency are passed.** This API is also used to create a mandate by passing the `mandate_object`. +/// **Creates a payment object when amount and currency are passed.** /// -/// To completely process a payment you will have to create a payment, attach a payment method, confirm and capture funds. +/// This API is also used to create a mandate by passing the `mandate_object`. /// -/// Depending on the user journey you wish to achieve, you may opt to complete all the steps in a single request by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request or you could use the following sequence of API requests to achieve the same: +/// Depending on the user journey you wish to achieve, you may opt to complete all the steps in a single request **by attaching a payment method, setting `confirm=true` and `capture_method = automatic`** in the *Payments/Create API* request. +/// +/// Otherwise, To completely process a payment you will have to **create a payment, attach a payment method, confirm and capture funds**. For that you could use the following sequence of API requests - /// /// 1. Payments - Create /// @@ -14,7 +16,9 @@ /// /// 4. Payments - Capture. /// -/// Use the client secret returned in this API along with your publishable key to make subsequent API calls from your client +/// You will require the 'API - Key' from the Hyperswitch dashboard to make the first call, and use the 'client secret' returned in this API along with your 'publishable key' to make subsequent API calls from your client. +/// +/// This page lists the various combinations in which the Payments - Create API can be used and the details about the various fields in the requests and responses. #[utoipa::path( post, path = "/payments", @@ -87,7 +91,7 @@ "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { - "acceptance_type": "offline", + "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", @@ -102,7 +106,7 @@ } }, "customer_acceptance": { - "acceptance_type": "offline", + "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", @@ -143,6 +147,14 @@ "card_cvc": "123" } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "setup_future_usage": "off_session" }) ) @@ -312,7 +324,7 @@ pub fn payments_update() {} } }, "customer_acceptance": { - "acceptance_type": "offline", + "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1",
2024-07-02T07:44:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Partially closes #5174 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
7004a802de2d30b97ecd37f57ba0e9c3aa962993
juspay/hyperswitch
juspay__hyperswitch-5156
Bug: [FEATURE] Add support for SMTP email server ### Feature Description Add support for sending emails with a custom SMTP server. (Currently only AWS SES is supported) ### Possible Implementation Could be implemented using `lettre` crate. Steps to implement: - Create the email building and sending logic - Impl the EmailClient trait - Add a new arm to the match statement in `create_email_client()` function ### 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 27b4158ba61..a2ede8c08c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1888,9 +1888,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.1.18" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62ac837cdb5cb22e10a256099b4fc502b1dfe560cb282963a974d7abd80e476" +checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" dependencies = [ "jobserver", "libc", @@ -1963,6 +1963,16 @@ dependencies = [ "phf_codegen", ] +[[package]] +name = "chumsky" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eebd66744a15ded14960ab4ccdbfb51ad3b81f51f3f04a80adac98c985396c9" +dependencies = [ + "hashbrown 0.14.5", + "stacker", +] + [[package]] name = "ciborium" version = "0.2.2" @@ -2962,6 +2972,22 @@ dependencies = [ "zeroize", ] +[[package]] +name = "email-encoding" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60d1d33cdaede7e24091f039632eb5d3c7469fe5b066a985281a34fc70fa317f" +dependencies = [ + "base64 0.22.1", + "memchr", +] + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" + [[package]] name = "encoding_rs" version = "0.8.34" @@ -3134,6 +3160,7 @@ dependencies = [ "hyper-proxy", "hyper-util", "hyperswitch_interfaces", + "lettre", "masking", "once_cell", "prost 0.13.2", @@ -3732,6 +3759,17 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "hostname" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c7c7c8ac16c798734b8a24560c1362120597c40d5e1459f09498f8f6c8f2ba" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "windows", +] + [[package]] name = "hsdev" version = "0.1.0" @@ -4117,6 +4155,124 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec 1.13.2", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.77", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -4133,6 +4289,27 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "idna" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec 1.13.2", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "ignore" version = "0.4.22" @@ -4456,6 +4633,31 @@ dependencies = [ "spin 0.9.8", ] +[[package]] +name = "lettre" +version = "0.11.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0161e452348e399deb685ba05e55ee116cae9410f4f51fe42d597361444521d9" +dependencies = [ + "base64 0.22.1", + "chumsky", + "email-encoding", + "email_address", + "fastrand 2.1.1", + "futures-util", + "hostname", + "httpdate", + "idna 1.0.3", + "mime", + "native-tls", + "nom", + "percent-encoding", + "quoted_printable", + "socket2", + "tokio 1.40.0", + "url", +] + [[package]] name = "libc" version = "0.2.158" @@ -4531,6 +4733,12 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +[[package]] +name = "litemap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" + [[package]] name = "local-channel" version = "0.1.5" @@ -5832,7 +6040,7 @@ checksum = "f8650aabb6c35b860610e9cff5dc1af886c9e25073b7b1712a68972af4281302" dependencies = [ "bytes 1.7.1", "heck 0.5.0", - "itertools 0.12.1", + "itertools 0.13.0", "log", "multimap", "once_cell", @@ -5865,7 +6073,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acf0c195eebb4af52c752bec4f52f645da98b6e92077a04110c7f349477ae5ac" dependencies = [ "anyhow", - "itertools 0.12.1", + "itertools 0.13.0", "proc-macro2", "quote", "syn 2.0.77", @@ -5880,6 +6088,15 @@ dependencies = [ "prost 0.13.2", ] +[[package]] +name = "psm" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200b9ff220857e53e184257720a14553b2f4aa02577d2ed9842d45d4b9654810" +dependencies = [ + "cc", +] + [[package]] name = "ptr_meta" version = "0.1.4" @@ -5949,6 +6166,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "quoted_printable" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "640c9bd8497b02465aeef5375144c26062e0dcd5939dfcbb0f5db76cb8c17c73" + [[package]] name = "r2d2" version = "0.8.10" @@ -7669,6 +7892,19 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +[[package]] +name = "stacker" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799c883d55abdb5e98af1a7b3f23b9b6de8ecada0ecac058672d7635eb48ca7b" +dependencies = [ + "cc", + "cfg-if 1.0.0", + "libc", + "psm", + "windows-sys 0.59.0", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -8092,6 +8328,16 @@ dependencies = [ "crunchy", ] +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -8939,7 +9185,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" dependencies = [ "form_urlencoded", - "idna", + "idna 0.5.0", "percent-encoding", "serde", ] @@ -8956,6 +9202,18 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517" +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" version = "0.2.2" @@ -9001,7 +9259,7 @@ version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da339118f018cc70ebf01fafc103360528aad53717e4bf311db929cb01cb9345" dependencies = [ - "idna", + "idna 0.5.0", "once_cell", "regex", "serde", @@ -9290,6 +9548,16 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +dependencies = [ + "windows-core", + "windows-targets 0.52.6", +] + [[package]] name = "windows-core" version = "0.52.0" @@ -9529,6 +9797,18 @@ dependencies = [ "url", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + [[package]] name = "ws2_32-sys" version = "0.2.1" @@ -9580,6 +9860,30 @@ dependencies = [ "linked-hash-map", ] +[[package]] +name = "yoke" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.77", + "synstructure 0.13.1", +] + [[package]] name = "zerocopy" version = "0.7.35" @@ -9601,12 +9905,55 @@ dependencies = [ "syn 2.0.77", ] +[[package]] +name = "zerofrom" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.77", + "synstructure 0.13.1", +] + [[package]] name = "zeroize" version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +[[package]] +name = "zerovec" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.77", +] + [[package]] name = "zstd" version = "0.13.2" diff --git a/config/development.toml b/config/development.toml index 6a6fda6755e..97739c3f5cd 100644 --- a/config/development.toml +++ b/config/development.toml @@ -311,7 +311,7 @@ wildcard_origin = true sender_email = "example@example.com" aws_region = "" allowed_unverified_days = 1 -active_email_client = "SES" +active_email_client = "NO_EMAIL_CLIENT" recon_recipient_email = "recon@example.com" prod_intent_recipient_email = "business@example.com" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 7adeee8a376..d71be958486 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -676,7 +676,7 @@ connector_list = "cybersource" sender_email = "example@example.com" # Sender email aws_region = "" # AWS region used by AWS SES allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email -active_email_client = "SES" # The currently active email client +active_email_client = "NO_EMAIL_CLIENT" # The currently active email client recon_recipient_email = "recon@example.com" # Recipient email for recon request email prod_intent_recipient_email = "business@example.com" # Recipient email for prod intent email diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 12b9dd3b0f3..e617dbe8351 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -29,6 +29,7 @@ error-stack = "0.4.1" hex = "0.4.3" hyper = "0.14.28" hyper-proxy = "0.9.1" +lettre = "0.11.10" once_cell = "1.19.0" serde = { version = "1.0.197", features = ["derive"] } thiserror = "1.0.58" diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs index 5751de95c12..2e05a26e1f1 100644 --- a/crates/external_services/src/email.rs +++ b/crates/external_services/src/email.rs @@ -7,6 +7,12 @@ use serde::Deserialize; /// Implementation of aws ses client pub mod ses; +/// Implementation of SMTP server client +pub mod smtp; + +/// Implementation of Email client when email support is disabled +pub mod no_email; + /// Custom Result type alias for Email operations. pub type EmailResult<T> = CustomResult<T, EmailError>; @@ -114,14 +120,27 @@ dyn_clone::clone_trait_object!(EmailClient<RichText = Body>); /// List of available email clients to choose from #[derive(Debug, Clone, Default, Deserialize)] -pub enum AvailableEmailClients { +#[serde(tag = "active_email_client")] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum EmailClientConfigs { #[default] + /// Default Email client to use when no client is specified + NoEmailClient, /// AWS ses email client - SES, + Ses { + /// AWS SES client configuration + aws_ses: ses::SESConfig, + }, + /// Other Simple SMTP server + Smtp { + /// SMTP server configuration + smtp: smtp::SmtpServerConfig, + }, } /// Struct that contains the settings required to construct an EmailClient. #[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] pub struct EmailSettings { /// The AWS region to send SES requests to. pub aws_region: String, @@ -132,11 +151,9 @@ pub struct EmailSettings { /// Sender email pub sender_email: String, - /// Configs related to AWS Simple Email Service - pub aws_ses: Option<ses::SESConfig>, - - /// The active email client to use - pub active_email_client: AvailableEmailClients, + #[serde(flatten)] + /// The client specific configurations + pub client_config: EmailClientConfigs, /// Recipient email for recon emails pub recon_recipient_email: pii::Email, @@ -145,6 +162,17 @@ pub struct EmailSettings { pub prod_intent_recipient_email: pii::Email, } +impl EmailSettings { + /// Validation for the Email client specific configurations + pub fn validate(&self) -> Result<(), &'static str> { + match &self.client_config { + EmailClientConfigs::Ses { ref aws_ses } => aws_ses.validate(), + EmailClientConfigs::Smtp { ref smtp } => smtp.validate(), + EmailClientConfigs::NoEmailClient => Ok(()), + } + } +} + /// Errors that could occur from EmailClient. #[derive(Debug, thiserror::Error)] pub enum EmailError { diff --git a/crates/external_services/src/email/no_email.rs b/crates/external_services/src/email/no_email.rs new file mode 100644 index 00000000000..6ec5d69e1ab --- /dev/null +++ b/crates/external_services/src/email/no_email.rs @@ -0,0 +1,37 @@ +use common_utils::{errors::CustomResult, pii}; +use router_env::logger; + +use crate::email::{EmailClient, EmailError, EmailResult, IntermediateString}; + +/// Client when email support is disabled +#[derive(Debug, Clone, Default, serde::Deserialize)] +pub struct NoEmailClient {} + +impl NoEmailClient { + /// Constructs a new client when email is disabled + pub async fn create() -> Self { + Self {} + } +} + +#[async_trait::async_trait] +impl EmailClient for NoEmailClient { + type RichText = String; + fn convert_to_rich_text( + &self, + intermediate_string: IntermediateString, + ) -> CustomResult<Self::RichText, EmailError> { + Ok(intermediate_string.into_inner()) + } + + async fn send_email( + &self, + _recipient: pii::Email, + _subject: String, + _body: Self::RichText, + _proxy_url: Option<&String>, + ) -> EmailResult<()> { + logger::info!("Email not sent as email support is disabled, please enable any of the supported email clients to send emails"); + Ok(()) + } +} diff --git a/crates/external_services/src/email/ses.rs b/crates/external_services/src/email/ses.rs index 73599b344cd..f9dcc8f26ad 100644 --- a/crates/external_services/src/email/ses.rs +++ b/crates/external_services/src/email/ses.rs @@ -7,7 +7,7 @@ use aws_sdk_sesv2::{ Client, }; use aws_sdk_sts::config::Credentials; -use common_utils::{errors::CustomResult, ext_traits::OptionExt, pii}; +use common_utils::{errors::CustomResult, pii}; use error_stack::{report, ResultExt}; use hyper::Uri; use masking::PeekInterface; @@ -19,6 +19,7 @@ use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, Intermed #[derive(Debug, Clone)] pub struct AwsSes { sender: String, + ses_config: SESConfig, settings: EmailSettings, } @@ -32,6 +33,21 @@ pub struct SESConfig { pub sts_role_session_name: String, } +impl SESConfig { + /// Validation for the SES client specific configs + pub fn validate(&self) -> Result<(), &'static str> { + use common_utils::{ext_traits::ConfigExt, fp_utils::when}; + + when(self.email_role_arn.is_default_or_empty(), || { + Err("email.aws_ses.email_role_arn must not be empty") + })?; + + when(self.sts_role_session_name.is_default_or_empty(), || { + Err("email.aws_ses.sts_role_session_name must not be empty") + }) + } +} + /// Errors that could occur during SES operations. #[derive(Debug, thiserror::Error)] pub enum AwsSesError { @@ -67,15 +83,20 @@ pub enum AwsSesError { impl AwsSes { /// Constructs a new AwsSes client - pub async fn create(conf: &EmailSettings, proxy_url: Option<impl AsRef<str>>) -> Self { + pub async fn create( + conf: &EmailSettings, + ses_config: &SESConfig, + proxy_url: Option<impl AsRef<str>>, + ) -> Self { // Build the client initially which will help us know if the email configuration is correct - Self::create_client(conf, proxy_url) + Self::create_client(conf, ses_config, proxy_url) .await .map_err(|error| logger::error!(?error, "Failed to initialize SES Client")) .ok(); Self { sender: conf.sender_email.clone(), + ses_config: ses_config.clone(), settings: conf.clone(), } } @@ -83,19 +104,13 @@ impl AwsSes { /// A helper function to create ses client pub async fn create_client( conf: &EmailSettings, + ses_config: &SESConfig, proxy_url: Option<impl AsRef<str>>, ) -> CustomResult<Client, AwsSesError> { let sts_config = Self::get_shared_config(conf.aws_region.to_owned(), proxy_url.as_ref())? .load() .await; - let ses_config = conf - .aws_ses - .as_ref() - .get_required_value("aws ses configuration") - .attach_printable("The selected email client is aws ses, but configuration is missing") - .change_context(AwsSesError::MissingConfigurationVariable("aws_ses"))?; - let role = aws_sdk_sts::Client::new(&sts_config) .assume_role() .role_arn(&ses_config.email_role_arn) @@ -219,7 +234,7 @@ impl EmailClient for AwsSes { ) -> EmailResult<()> { // Not using the same email client which was created at startup as the role session would expire // Create a client every time when the email is being sent - let email_client = Self::create_client(&self.settings, proxy_url) + let email_client = Self::create_client(&self.settings, &self.ses_config, proxy_url) .await .change_context(EmailError::ClientBuildingFailure)?; diff --git a/crates/external_services/src/email/smtp.rs b/crates/external_services/src/email/smtp.rs new file mode 100644 index 00000000000..33ab89f4571 --- /dev/null +++ b/crates/external_services/src/email/smtp.rs @@ -0,0 +1,189 @@ +use std::time::Duration; + +use common_utils::{errors::CustomResult, pii}; +use error_stack::ResultExt; +use lettre::{ + address::AddressError, + error, + message::{header::ContentType, Mailbox}, + transport::smtp::{self, authentication::Credentials}, + Message, SmtpTransport, Transport, +}; +use masking::{PeekInterface, Secret}; + +use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString}; + +/// Client for SMTP server operation +#[derive(Debug, Clone, Default, serde::Deserialize)] +pub struct SmtpServer { + /// sender email id + pub sender: String, + /// SMTP server specific configs + pub smtp_config: SmtpServerConfig, +} + +impl SmtpServer { + /// A helper function to create SMTP server client + pub fn create_client(&self) -> Result<SmtpTransport, SmtpError> { + let host = self.smtp_config.host.clone(); + let port = self.smtp_config.port; + let timeout = Some(Duration::from_secs(self.smtp_config.timeout)); + let credentials = self + .smtp_config + .username + .clone() + .zip(self.smtp_config.password.clone()) + .map(|(username, password)| { + Credentials::new(username.peek().to_owned(), password.peek().to_owned()) + }); + match &self.smtp_config.connection { + SmtpConnection::StartTls => match credentials { + Some(credentials) => Ok(SmtpTransport::starttls_relay(&host) + .map_err(SmtpError::ConnectionFailure)? + .port(port) + .timeout(timeout) + .credentials(credentials) + .build()), + None => Ok(SmtpTransport::starttls_relay(&host) + .map_err(SmtpError::ConnectionFailure)? + .port(port) + .timeout(timeout) + .build()), + }, + SmtpConnection::Plaintext => match credentials { + Some(credentials) => Ok(SmtpTransport::builder_dangerous(&host) + .port(port) + .timeout(timeout) + .credentials(credentials) + .build()), + None => Ok(SmtpTransport::builder_dangerous(&host) + .port(port) + .timeout(timeout) + .build()), + }, + } + } + /// Constructs a new SMTP client + pub async fn create(conf: &EmailSettings, smtp_config: SmtpServerConfig) -> Self { + Self { + sender: conf.sender_email.clone(), + smtp_config: smtp_config.clone(), + } + } + /// helper function to convert email id into Mailbox + fn to_mail_box(email: String) -> EmailResult<Mailbox> { + Ok(Mailbox::new( + None, + email + .parse() + .map_err(SmtpError::EmailParsingFailed) + .change_context(EmailError::EmailSendingFailure)?, + )) + } +} +/// Struct that contains the SMTP server specific configs required +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct SmtpServerConfig { + /// hostname of the SMTP server eg: smtp.gmail.com + pub host: String, + /// portname of the SMTP server eg: 25 + pub port: u16, + /// timeout for the SMTP server connection in seconds eg: 10 + pub timeout: u64, + /// Username name of the SMTP server + pub username: Option<Secret<String>>, + /// Password of the SMTP server + pub password: Option<Secret<String>>, + /// Connection type of the SMTP server + #[serde(default)] + pub connection: SmtpConnection, +} + +/// Enum that contains the connection types of the SMTP server +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SmtpConnection { + #[default] + /// Plaintext connection which MUST then successfully upgrade to TLS via STARTTLS + StartTls, + /// Plaintext connection (very insecure) + Plaintext, +} + +impl SmtpServerConfig { + /// Validation for the SMTP server client specific configs + pub fn validate(&self) -> Result<(), &'static str> { + use common_utils::{ext_traits::ConfigExt, fp_utils::when}; + when(self.host.is_default_or_empty(), || { + Err("email.smtp.host must not be empty") + })?; + self.username.clone().zip(self.password.clone()).map_or( + Ok(()), + |(username, password)| { + when(username.peek().is_default_or_empty(), || { + Err("email.smtp.username must not be empty") + })?; + when(password.peek().is_default_or_empty(), || { + Err("email.smtp.password must not be empty") + }) + }, + )?; + Ok(()) + } +} + +#[async_trait::async_trait] +impl EmailClient for SmtpServer { + type RichText = String; + fn convert_to_rich_text( + &self, + intermediate_string: IntermediateString, + ) -> CustomResult<Self::RichText, EmailError> { + Ok(intermediate_string.into_inner()) + } + + async fn send_email( + &self, + recipient: pii::Email, + subject: String, + body: Self::RichText, + _proxy_url: Option<&String>, + ) -> EmailResult<()> { + // Create a client every time when the email is being sent + let email_client = + Self::create_client(self).change_context(EmailError::EmailSendingFailure)?; + + let email = Message::builder() + .to(Self::to_mail_box(recipient.peek().to_string())?) + .from(Self::to_mail_box(self.sender.clone())?) + .subject(subject) + .header(ContentType::TEXT_HTML) + .body(body) + .map_err(SmtpError::MessageBuildingFailed) + .change_context(EmailError::EmailSendingFailure)?; + + email_client + .send(&email) + .map_err(SmtpError::SendingFailure) + .change_context(EmailError::EmailSendingFailure)?; + Ok(()) + } +} + +/// Errors that could occur during SES operations. +#[derive(Debug, thiserror::Error)] +pub enum SmtpError { + /// An error occurred in the SMTP while sending email. + #[error("Failed to Send Email {0:?}")] + SendingFailure(smtp::Error), + /// An error occurred in the SMTP while building the message content. + #[error("Failed to create connection {0:?}")] + ConnectionFailure(smtp::Error), + /// An error occurred in the SMTP while building the message content. + #[error("Failed to Build Email content {0:?}")] + MessageBuildingFailed(error::Error), + /// An error occurred in the SMTP while building the message content. + #[error("Failed to parse given email {0:?}")] + EmailParsingFailed(AddressError), +} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index f675aad11a7..76b58f5b67b 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -881,6 +881,10 @@ impl Settings<SecuredSecret> { .transpose()?; self.key_manager.get_inner().validate()?; + #[cfg(feature = "email")] + self.email + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; Ok(()) } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1d7e9727cf3..baa2ba4ae15 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -8,7 +8,9 @@ use common_enums::TransactionType; #[cfg(feature = "partial-auth")] use common_utils::crypto::Blake3; #[cfg(feature = "email")] -use external_services::email::{ses::AwsSes, EmailService}; +use external_services::email::{ + no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService, +}; use external_services::{file_storage::FileStorageInterface, grpc_client::GrpcClients}; use hyperswitch_interfaces::{ encryption_interface::EncryptionManagementInterface, @@ -97,7 +99,7 @@ pub struct SessionState { pub api_client: Box<dyn crate::services::ApiClient>, pub event_handler: EventsHandler, #[cfg(feature = "email")] - pub email_client: Arc<dyn EmailService>, + pub email_client: Arc<Box<dyn EmailService>>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, pub file_storage_client: Arc<dyn FileStorageInterface>, @@ -195,7 +197,7 @@ pub struct AppState { pub conf: Arc<settings::Settings<RawSecret>>, pub event_handler: EventsHandler, #[cfg(feature = "email")] - pub email_client: Arc<dyn EmailService>, + pub email_client: Arc<Box<dyn EmailService>>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] pub pools: HashMap<String, AnalyticsProvider>, @@ -215,7 +217,7 @@ pub trait AppStateInfo { fn conf(&self) -> settings::Settings<RawSecret>; fn event_handler(&self) -> EventsHandler; #[cfg(feature = "email")] - fn email_client(&self) -> Arc<dyn EmailService>; + fn email_client(&self) -> Arc<Box<dyn EmailService>>; fn add_request_id(&mut self, request_id: RequestId); fn add_flow_name(&mut self, flow_name: String); fn get_request_id(&self) -> Option<String>; @@ -232,7 +234,7 @@ impl AppStateInfo for AppState { self.conf.as_ref().to_owned() } #[cfg(feature = "email")] - fn email_client(&self) -> Arc<dyn EmailService> { + fn email_client(&self) -> Arc<Box<dyn EmailService>> { self.email_client.to_owned() } fn event_handler(&self) -> EventsHandler { @@ -258,11 +260,22 @@ impl AsRef<Self> for AppState { } #[cfg(feature = "email")] -pub async fn create_email_client(settings: &settings::Settings<RawSecret>) -> impl EmailService { - match settings.email.active_email_client { - external_services::email::AvailableEmailClients::SES => { - AwsSes::create(&settings.email, settings.proxy.https_url.to_owned()).await +pub async fn create_email_client( + settings: &settings::Settings<RawSecret>, +) -> Box<dyn EmailService> { + match &settings.email.client_config { + EmailClientConfigs::Ses { aws_ses } => Box::new( + AwsSes::create( + &settings.email, + aws_ses, + settings.proxy.https_url.to_owned(), + ) + .await, + ), + EmailClientConfigs::Smtp { smtp } => { + Box::new(SmtpServer::create(&settings.email, smtp.clone()).await) } + EmailClientConfigs::NoEmailClient => Box::new(NoEmailClient::create().await), } } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 934b072f14a..288e72164cf 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -384,7 +384,7 @@ public = { base_url = "http://localhost:8080", schema = "public", redis_key_pref sender_email = "example@example.com" aws_region = "" allowed_unverified_days = 1 -active_email_client = "SES" +active_email_client = "NO_EMAIL_CLIENT" recon_recipient_email = "recon@example.com" prod_intent_recipient_email = "business@example.com"
2024-11-19T19:55:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add SMTP support to allow mails through self-hosted/custom SMTP server #5156 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Hyperswitch currently supports only AWS SES to send emails, other open users who want to use some custom SMTP server will have no way to configure it. With this implementation users can change below config to use their own SMTP server. ``` [email] active_email_client = "SMTP" [email.smtp] host = "127.0.0.1" port = 1025 timeout = 10 connection = "plaintext" #currently plaintext and starttls are supported ``` ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Setup mailhog to test emails locally ```docker run -p 1025:1025 -p 8025:8025 mailhog/mailhog``` 1. Check if is possible to disable email with the env config ``` [email] active_email_client = "NO_EMAIL_CLIENT" ``` Start the server with `cargo r` and there should be no error 2. Check the SMTP server without authentication and No TLS with the above configs Start the server with `cargo r`, and there should be no error Start the dashboard and change the below config ``` [user] base_url = "http://localhost:9000" ``` - Check if signup email is sent correctly - Check if reset password email is sent correctly: Profile -> Reset Password - Check if Forgot password email is sent correctly - Check if magic link is working - Check if invite user email is sent correctly <img width="785" alt="Screenshot 2024-11-20 at 01 24 02" src="https://github.com/user-attachments/assets/feb21b27-07c4-4135-8ff2-bd114a704fcf"> <img width="1342" alt="Screenshot 2024-11-20 at 01 24 28" src="https://github.com/user-attachments/assets/7c141481-7a81-41cb-9253-b6fc2a6a07b7"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
43d87913ab3d177a6d193b3e475c96609cc09a28
juspay/hyperswitch
juspay__hyperswitch-5146
Bug: fix: cover sso nitpicks and todo changes Nitpicks - change parsing login for configs - refactor terminate auth select - clear cookie in rotate and reset password
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 3e9145c2d33..ff1477aa3c9 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -4,7 +4,6 @@ use api_models::{ payments::RedirectionResponse, user::{self as user_api, InviteMultipleUserResponse}, }; -use common_utils::ext_traits::ValueExt; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; use diesel_models::{ @@ -481,7 +480,7 @@ pub async fn rotate_password( .await .map_err(|e| logger::error!(?e)); - Ok(ApplicationResponse::StatusOk) + auth::cookies::remove_cookie_response() } #[cfg(feature = "email")] @@ -544,7 +543,7 @@ pub async fn reset_password_token_only_flow( .await .map_err(|e| logger::error!(?e)); - Ok(ApplicationResponse::StatusOk) + auth::cookies::remove_cookie_response() } #[cfg(feature = "email")] @@ -597,7 +596,7 @@ pub async fn reset_password( .await .map_err(|e| logger::error!(?e)); - Ok(ApplicationResponse::StatusOk) + auth::cookies::remove_cookie_response() } pub async fn invite_multiple_user( @@ -2174,10 +2173,10 @@ pub async fn list_user_authentication_methods( .map(|auth_method| { let auth_name = match (auth_method.auth_type, auth_method.public_config) { (common_enums::UserAuthType::OpenIdConnect, Some(config)) => { - let open_id_public_config: user_api::OpenIdConnectPublicConfig = config - .parse_value("OpenIdConnectPublicConfig") - .change_context(UserErrors::InternalServerError) - .attach_printable("unable to parse generic data value")?; + let open_id_public_config = + serde_json::from_value::<user_api::OpenIdConnectPublicConfig>(config) + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; Ok(Some(open_id_public_config.name)) } @@ -2216,13 +2215,14 @@ pub async fn get_sso_auth_url( utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) .await?; - let open_id_public_config: user_api::OpenIdConnectPublicConfig = user_authentication_method - .public_config - .ok_or(UserErrors::InternalServerError) - .attach_printable("Public config not present")? - .parse_value("OpenIdConnectPublicConfig") - .change_context(UserErrors::InternalServerError) - .attach_printable("unable to parse OpenIdConnectPublicConfig")?; + let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( + user_authentication_method + .public_config + .ok_or(UserErrors::InternalServerError) + .attach_printable("Public config not present")?, + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; let oidc_state = Secret::new(nanoid::nanoid!()); utils::user::set_sso_id_in_redis(&state, oidc_state.clone(), request.id).await?; @@ -2267,13 +2267,14 @@ pub async fn sso_sign( utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) .await?; - let open_id_public_config: user_api::OpenIdConnectPublicConfig = user_authentication_method - .public_config - .ok_or(UserErrors::InternalServerError) - .attach_printable("Public config not present")? - .parse_value("OpenIdConnectPublicConfig") - .change_context(UserErrors::InternalServerError) - .attach_printable("unable to parse OpenIdConnectPublicConfig")?; + let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( + user_authentication_method + .public_config + .ok_or(UserErrors::InternalServerError) + .attach_printable("Public config not present")?, + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; let redirect_url = utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string()); @@ -2329,14 +2330,14 @@ pub async fn terminate_auth_select( .store .get_user_authentication_method_by_id(&req.id) .await - .change_context(UserErrors::InternalServerError)?; + .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; // Skip SSO if continue with password(TOTP) if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) - && user_authentication_method.auth_type != common_enums::UserAuthType::OpenIdConnect + && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) { next_flow = next_flow.skip(user_from_db, &state).await?; } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 6b957281f76..e80fe8d1de8 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -1,7 +1,8 @@ use std::{collections::HashMap, sync::Arc}; use api_models::user as user_api; -use common_utils::{errors::CustomResult, ext_traits::ValueExt}; +use common_enums::UserAuthType; +use common_utils::errors::CustomResult; use diesel_models::{encryption::Encryption, enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; @@ -206,7 +207,7 @@ pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnect .attach_printable("Failed to get redis connection") } -impl ForeignFrom<user_api::AuthConfig> for common_enums::UserAuthType { +impl ForeignFrom<user_api::AuthConfig> for UserAuthType { fn foreign_from(from: user_api::AuthConfig) -> Self { match from { user_api::AuthConfig::OpenIdConnect { .. } => Self::OpenIdConnect, @@ -244,8 +245,7 @@ pub async fn decrypt_oidc_private_config( .into_inner() .expose(); - private_config - .parse_value("OpenIdConnectPrivateConfig") + serde_json::from_value::<user_api::OpenIdConnectPrivateConfig>(private_config) .change_context(UserErrors::InternalServerError) .attach_printable("unable to parse OpenIdConnectPrivateConfig") } @@ -286,3 +286,10 @@ fn get_oidc_key(oidc_state: &str) -> String { pub fn get_oidc_sso_redirect_url(state: &SessionState, provider: &str) -> String { format!("{}/redirect/oidc/{}", state.conf.user.base_url, provider) } + +pub fn is_sso_auth_type(auth_type: &UserAuthType) -> bool { + match auth_type { + UserAuthType::OpenIdConnect => true, + UserAuthType::Password | UserAuthType::MagicLink => false, + } +}
2024-06-27T13:08:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The PR - removes cookie after rotate password and reset password - refactor parsing for sso config, now it uses `serde json from value` instead of `parse value` - refactors terminate auth select - send bad request instead of internal server error if invalid id is passed to auth/select ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context closes #5146 ## How did you test it? For bad request id for in auth select: ``` curl --location 'http://localhost:8080/user/auth/select' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT' \ --data '{ "id":"wrong id" }' ``` Response ``` { "error": { "type": "invalid_request", "message": "Invalid user auth method operation", "code": "UR_44" } } ``` For valid id Response token type can be `sso` or `totp`, (tested for both valid ids from db to get correct token type) ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6InNzbyIsIm9yaWdpbiI6ImFjY2VwdF9pbnZpdGF0aW9uX2Zyb21fZW1haWwiLCJwYXRoIjpbImF1dGhfc2VsZWN0Il0sImV4cCI6MTcxOTY2NjMxNX0.wz8bA3_xqD1J59t3N7jhMCpC-uQDZE2edMED93f8RrY", "token_type": "sso" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d4dba55fedc37ba9d1d54d28456ca17851ab9881
juspay/hyperswitch
juspay__hyperswitch-5141
Bug: [FEATURE] Add support for changing the decryption scheme of the locker ## Description Currently, locker uses `RSA_OAEP` for encryption which is deprecated. To allow for seamless migration we are adding a configuration to allow for changing the decryption scheme in hyperswitch side
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 35bfbc88f69..95b585d3445 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -69,6 +69,7 @@ impl Default for super::settings::Locker { locker_enabled: true, //Time to live for storage entries in locker ttl_for_storage_in_secs: 60 * 60 * 24 * 365 * 7, + decryption_scheme: Default::default(), } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 0569c4dbed6..2bbb50d6812 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -497,6 +497,16 @@ pub struct Locker { pub locker_signing_key_id: String, pub locker_enabled: bool, pub ttl_for_storage_in_secs: i64, + pub decryption_scheme: DecryptionScheme, +} + +#[derive(Debug, Deserialize, Clone, Default)] +pub enum DecryptionScheme { + #[default] + #[serde(rename = "RSA-OAEP")] + RsaOaep, + #[serde(rename = "RSA-OAEP-256")] + RsaOaep256, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rs index c3499445602..d17322f2be5 100644 --- a/crates/router/src/core/blocklist/transformers.rs +++ b/crates/router/src/core/blocklist/transformers.rs @@ -144,11 +144,15 @@ async fn call_to_locker_for_fingerprint( .get_response_inner("JweBody") .change_context(errors::VaultError::GenerateFingerprintFailed)?; - let decrypted_payload = - decrypt_generate_fingerprint_response_payload(jwekey, jwe_body, Some(locker_choice)) - .await - .change_context(errors::VaultError::GenerateFingerprintFailed) - .attach_printable("Error getting decrypted fingerprint response payload")?; + let decrypted_payload = decrypt_generate_fingerprint_response_payload( + jwekey, + jwe_body, + Some(locker_choice), + locker.decryption_scheme.clone(), + ) + .await + .change_context(errors::VaultError::GenerateFingerprintFailed) + .attach_printable("Error getting decrypted fingerprint response payload")?; let generate_fingerprint_response: blocklist::GenerateFingerprintResponsePayload = decrypted_payload .parse_struct("GenerateFingerprintResponse") @@ -159,9 +163,9 @@ async fn call_to_locker_for_fingerprint( async fn decrypt_generate_fingerprint_response_payload( jwekey: &settings::Jwekey, - jwe_body: encryption::JweBody, locker_choice: Option<api_enums::LockerChoice>, + decryption_scheme: settings::DecryptionScheme, ) -> CustomResult<String, errors::VaultError> { let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault); @@ -174,7 +178,10 @@ async fn decrypt_generate_fingerprint_response_payload( let private_key = jwekey.vault_private_key.peek().as_bytes(); let jwt = payment_methods::get_dotted_jwe(jwe_body); - let alg = jwe::RSA_OAEP; + let alg = match decryption_scheme { + settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP, + settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256, + }; let jwe_decrypted = encryption::decrypt_jwe( &jwt, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 53b0063c6ef..6b2b8a3d6f6 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1315,11 +1315,15 @@ pub async fn get_payment_method_from_hs_locker<'a>( let jwe_body: services::JweBody = response .get_response_inner("JweBody") .change_context(errors::VaultError::FetchPaymentMethodFailed)?; - let decrypted_payload = - payment_methods::get_decrypted_response_payload(jwekey, jwe_body, locker_choice) - .await - .change_context(errors::VaultError::FetchPaymentMethodFailed) - .attach_printable("Error getting decrypted response payload for get card")?; + let decrypted_payload = payment_methods::get_decrypted_response_payload( + jwekey, + jwe_body, + locker_choice, + locker.decryption_scheme.clone(), + ) + .await + .change_context(errors::VaultError::FetchPaymentMethodFailed) + .attach_printable("Error getting decrypted response payload for get card")?; let get_card_resp: payment_methods::RetrieveCardResp = decrypted_payload .parse_struct("RetrieveCardResp") .change_context(errors::VaultError::FetchPaymentMethodFailed) @@ -1368,11 +1372,15 @@ pub async fn call_to_locker_hs<'a>( .get_response_inner("JweBody") .change_context(errors::VaultError::FetchCardFailed)?; - let decrypted_payload = - payment_methods::get_decrypted_response_payload(jwekey, jwe_body, Some(locker_choice)) - .await - .change_context(errors::VaultError::SaveCardFailed) - .attach_printable("Error getting decrypted response payload")?; + let decrypted_payload = payment_methods::get_decrypted_response_payload( + jwekey, + jwe_body, + Some(locker_choice), + locker.decryption_scheme.clone(), + ) + .await + .change_context(errors::VaultError::SaveCardFailed) + .attach_printable("Error getting decrypted response payload")?; let stored_card_resp: payment_methods::StoreCardResp = decrypted_payload .parse_struct("StoreCardResp") .change_context(errors::VaultError::ResponseDeserializationFailed)?; @@ -1449,11 +1457,15 @@ pub async fn get_card_from_hs_locker<'a>( let jwe_body: services::JweBody = response .get_response_inner("JweBody") .change_context(errors::VaultError::FetchCardFailed)?; - let decrypted_payload = - payment_methods::get_decrypted_response_payload(jwekey, jwe_body, Some(locker_choice)) - .await - .change_context(errors::VaultError::FetchCardFailed) - .attach_printable("Error getting decrypted response payload for get card")?; + let decrypted_payload = payment_methods::get_decrypted_response_payload( + jwekey, + jwe_body, + Some(locker_choice), + locker.decryption_scheme.clone(), + ) + .await + .change_context(errors::VaultError::FetchCardFailed) + .attach_printable("Error getting decrypted response payload for get card")?; let get_card_resp: payment_methods::RetrieveCardResp = decrypted_payload .parse_struct("RetrieveCardResp") .change_context(errors::VaultError::FetchCardFailed)?; @@ -1503,6 +1515,7 @@ pub async fn delete_card_from_hs_locker<'a>( jwekey, jwe_body, Some(api_enums::LockerChoice::HyperswitchCardVault), + locker.decryption_scheme.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index ca0cbb2a0f8..887c02dd023 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -199,6 +199,7 @@ pub async fn get_decrypted_response_payload( jwekey: &settings::Jwekey, jwe_body: encryption::JweBody, locker_choice: Option<api_enums::LockerChoice>, + decryption_scheme: settings::DecryptionScheme, ) -> CustomResult<String, errors::VaultError> { let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault); @@ -211,7 +212,10 @@ pub async fn get_decrypted_response_payload( let private_key = jwekey.vault_private_key.peek().as_bytes(); let jwt = get_dotted_jwe(jwe_body); - let alg = jwe::RSA_OAEP; + let alg = match decryption_scheme { + settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP, + settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256, + }; let jwe_decrypted = encryption::decrypt_jwe( &jwt,
2024-06-27T09:04:31Z
…e used by the locker ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add support for `RSA-OAEP-256` while decrypting the locker response as a configuration <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? Optional configuration, no tests needed ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d4dba55fedc37ba9d1d54d28456ca17851ab9881
juspay/hyperswitch
juspay__hyperswitch-5138
Bug: Skip session to call pay when the browser is not `Safari` Currently, the Apple Pay session call is mandatory in all cases. This requirement also mandates configuring the initiative_context, which is the domain name where the Apple Pay payment is being processed. However, in the case of an iOS app, a domain is not required, so this field can be made optional. Additionally, in this case, the session call to Apple Pay can be skipped. On the web, Apple Pay is supported only in Safari. Therefore, the session call should be skipped in web environments when the browser is not Safari.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 777e876b1b5..bf275a0dd0f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -20,6 +20,7 @@ use serde::{ ser::Serializer, Deserialize, Deserializer, Serialize, }; +use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; @@ -592,6 +593,8 @@ pub struct HeaderPayload { pub client_source: Option<String>, pub client_version: Option<String>, pub x_hs_latency: Option<bool>, + pub browser_name: Option<api_enums::BrowserName>, + pub x_client_platform: Option<api_enums::ClientPlatform>, } impl HeaderPayload { @@ -4299,14 +4302,21 @@ pub struct SessionTokenInfo { pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, - pub initiative: String, - pub initiative_context: String, + pub initiative: ApplepayInitiative, + pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ApplepayInitiative { + Web, + Ios, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { @@ -4421,7 +4431,9 @@ pub struct PaypalSessionTokenResponse { #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay - pub session_token_data: ApplePaySessionResponse, + /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved + #[serde(skip_serializing_if = "Option::is_none")] + pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index c3aa895e1ce..5ee0bae6d61 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2258,6 +2258,24 @@ pub enum PaymentSource { ExternalAuthenticator, } +#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] +pub enum BrowserName { + #[default] + Safari, + #[serde(other)] + Unknown, +} + +#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] +#[strum(serialize_all = "snake_case")] +pub enum ClientPlatform { + #[default] + Web, + Ios, + #[serde(other)] + Unknown, +} + impl PaymentSource { pub fn is_for_internal_use_only(&self) -> bool { match self { diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 0c24fba34cf..a259559c51d 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -317,6 +317,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::ApplepayConnectorMetadataRequest, api_models::payments::SessionTokenInfo, api_models::payments::PaymentProcessingDetailsAt, + api_models::payments::ApplepayInitiative, api_models::payments::PaymentProcessingDetails, api_models::payments::PaymentMethodDataResponseWithBilling, api_models::payments::PaymentMethodDataResponse, diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 909e8120c6e..fbc7c661e4c 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -461,10 +461,16 @@ impl TryFrom<&types::PaymentsSessionRouterData> for BluesnapCreateWalletToken { }) } }?; + let domain_name = session_token_data.initiative_context.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "apple pay initiative_context", + }, + )?; + Ok(Self { wallet_type: "APPLE_PAY".to_string(), validation_url: consts::APPLEPAY_VALIDATION_URL.to_string().into(), - domain_name: session_token_data.initiative_context, + domain_name, display_name: Some(session_token_data.display_name), }) } @@ -529,8 +535,8 @@ impl response: Ok(types::PaymentsResponseData::SessionResponse { session_token: api::SessionToken::ApplePay(Box::new( payments::ApplepaySessionTokenResponse { - session_token_data: payments::ApplePaySessionResponse::NoThirdPartySdk( - session_response, + session_token_data: Some( + payments::ApplePaySessionResponse::NoThirdPartySdk(session_response), ), payment_request_data: Some(payments::ApplePayPaymentRequest { country_code: item.data.get_billing_country()?, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 5cb025816d6..47942d7de43 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -553,8 +553,9 @@ impl<F> _, ))) => Some(api_models::payments::SessionToken::ApplePay(Box::new( api_models::payments::ApplepaySessionTokenResponse { - session_token_data: + session_token_data: Some( api_models::payments::ApplePaySessionResponse::NoSessionResponse, + ), payment_request_data: Some( api_models::payments::ApplePayPaymentRequest { country_code: item.data.get_billing_country()?, diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index b48c52c76ff..77d85393d29 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -1209,12 +1209,13 @@ pub fn get_apple_pay_session<F, T>( pre_processing_id: types::PreprocessingResponseId::ConnectorTransactionId(instance_id), session_token: Some(types::api::SessionToken::ApplePay(Box::new( api_models::payments::ApplepaySessionTokenResponse { - session_token_data: + session_token_data: Some( api_models::payments::ApplePaySessionResponse::ThirdPartySdk( api_models::payments::ThirdPartySdkSessionResponse { secrets: secrets.to_owned().into(), }, ), + ), payment_request_data: Some(api_models::payments::ApplePayPaymentRequest { country_code: apple_pay_init_result.country_code, currency_code: apple_pay_init_result.currency_code, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 459ada8fb4f..8290177f21b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -461,6 +461,7 @@ where &customer, session_surcharge_details, &business_profile, + header_payload.clone(), )) .await? } @@ -1610,6 +1611,7 @@ where call_connector_action, connector_request, business_profile, + header_payload.clone(), ) .await } else { @@ -1673,6 +1675,7 @@ pub async fn call_multiple_connectors_service<F, Op, Req>( customer: &Option<domain::Customer>, session_surcharge_details: Option<api::SessionSurchargeDetails>, business_profile: &storage::business_profile::BusinessProfile, + header_payload: HeaderPayload, ) -> RouterResult<PaymentData<F>> where Op: Debug, @@ -1736,6 +1739,7 @@ where CallConnectorAction::Trigger, None, business_profile, + header_payload.clone(), ); join_handlers.push(res); diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index f4609465200..aa5be3924a9 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -47,6 +47,7 @@ pub trait Feature<F, T> { call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, business_profile: &storage::business_profile::BusinessProfile, + header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> where Self: Sized, diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index f15274ba5be..f4f8409912e 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -52,6 +52,7 @@ impl Feature<api::Approve, types::PaymentsApproveData> _call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 5909b0841fb..23971f3696c 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -65,6 +65,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Authorize, diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 0914bd0e901..d61730117a8 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -52,6 +52,7 @@ impl Feature<api::Void, types::PaymentsCancelData> call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { metrics::PAYMENT_CANCEL_COUNT.add( &metrics::CONTEXT, diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index a2c2abe7d8a..3e098043544 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -52,6 +52,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData> call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Capture, 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 e735278609b..bb56cb5a7c5 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -66,6 +66,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::CompleteAuthorize, diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs index 673bb8a1ace..2aa808f9532 100644 --- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs +++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs @@ -59,6 +59,7 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::IncrementalAuthorization, diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index eae1d8cfd7f..5b0d1a48e67 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -55,6 +55,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PSync, diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index 020e6ff101d..cb1dcd5b19f 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -51,6 +51,7 @@ impl Feature<api::Reject, types::PaymentsRejectData> _call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 0774f0a8593..1223d861ebd 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -65,6 +65,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, business_profile: &storage::business_profile::BusinessProfile, + header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { metrics::SESSION_TOKEN_CREATED.add( &metrics::CONTEXT, @@ -77,6 +78,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio Some(true), call_connector_action, business_profile, + header_payload, ) .await } @@ -155,6 +157,7 @@ async fn create_applepay_session_token( router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, business_profile: &storage::business_profile::BusinessProfile, + header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<types::PaymentsSessionRouterData> { let delayed_response = is_session_response_delayed(state, connector); if delayed_response { @@ -188,9 +191,10 @@ async fn create_applepay_session_token( // Get payment request data , apple pay session request and merchant keys let ( payment_request_data, - apple_pay_session_request, + apple_pay_session_request_optional, apple_pay_merchant_cert, apple_pay_merchant_cert_key, + apple_pay_merchant_identifier, merchant_business_country, ) = match apple_pay_metadata { payment_types::ApplepaySessionTokenMetadata::ApplePayCombined( @@ -213,7 +217,7 @@ async fn create_applepay_session_token( let merchant_business_country = session_token_data.merchant_business_country; let apple_pay_session_request = get_session_request_for_simplified_apple_pay( - merchant_identifier, + merchant_identifier.clone(), session_token_data, ); @@ -233,9 +237,10 @@ async fn create_applepay_session_token( ( payment_request_data, - apple_pay_session_request, + Ok(apple_pay_session_request), apple_pay_merchant_cert, apple_pay_merchant_cert_key, + merchant_identifier, merchant_business_country, ) } @@ -255,6 +260,7 @@ async fn create_applepay_session_token( apple_pay_session_request, session_token_data.certificate.clone(), session_token_data.certificate_keys, + session_token_data.merchant_identifier, merchant_business_country, ) } @@ -273,7 +279,11 @@ async fn create_applepay_session_token( apple_pay_metadata.payment_request_data, apple_pay_session_request, apple_pay_metadata.session_token_data.certificate.clone(), - apple_pay_metadata.session_token_data.certificate_keys, + apple_pay_metadata + .session_token_data + .certificate_keys + .clone(), + apple_pay_metadata.session_token_data.merchant_identifier, merchant_business_country, ) } @@ -323,48 +333,63 @@ async fn create_applepay_session_token( amount_info, payment_request_data, router_data.request.to_owned(), - apple_pay_session_request.merchant_identifier.as_str(), + apple_pay_merchant_identifier.as_str(), merchant_business_country, required_billing_contact_fields, required_shipping_contact_fields, )?; - let applepay_session_request = build_apple_pay_session_request( - state, - apple_pay_session_request, - apple_pay_merchant_cert, - apple_pay_merchant_cert_key, - )?; - let response = services::call_connector_api( - state, - applepay_session_request, - "create_apple_pay_session_token", - ) - .await; - - // logging the error if present in session call response - log_session_response_if_error(&response); - - let apple_pay_session_response = response - .ok() - .and_then(|apple_pay_res| { - apple_pay_res - .map(|res| { - let response: Result< - payment_types::NoThirdPartySdkSessionResponse, - Report<common_utils::errors::ParsingError>, - > = res.response.parse_struct("NoThirdPartySdkSessionResponse"); - - // logging the parsing failed error - if let Err(error) = response.as_ref() { - logger::error!(?error); - }; - - response.ok() - }) + let apple_pay_session_response = match ( + header_payload.browser_name, + header_payload.x_client_platform, + ) { + (Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web)) + | (None, None) => { + let apple_pay_session_request = apple_pay_session_request_optional + .attach_printable("Failed to obtain apple pay session request")?; + let applepay_session_request = build_apple_pay_session_request( + state, + apple_pay_session_request, + apple_pay_merchant_cert, + apple_pay_merchant_cert_key, + )?; + + let response = services::call_connector_api( + state, + applepay_session_request, + "create_apple_pay_session_token", + ) + .await; + + // logging the error if present in session call response + log_session_response_if_error(&response); + + response .ok() - }) - .flatten(); + .and_then(|apple_pay_res| { + apple_pay_res + .map(|res| { + let response: Result< + payment_types::NoThirdPartySdkSessionResponse, + Report<common_utils::errors::ParsingError>, + > = res.response.parse_struct("NoThirdPartySdkSessionResponse"); + + // logging the parsing failed error + if let Err(error) = response.as_ref() { + logger::error!(?error); + }; + + response.ok() + }) + .ok() + }) + .flatten() + } + _ => { + logger::debug!("Skipping apple pay session call based on the browser name"); + None + } + }; let session_response = apple_pay_session_response.map(payment_types::ApplePaySessionResponse::NoThirdPartySdk); @@ -394,13 +419,17 @@ fn get_session_request_for_simplified_apple_pay( fn get_session_request_for_manual_apple_pay( session_token_data: payment_types::SessionTokenInfo, -) -> payment_types::ApplepaySessionRequest { - payment_types::ApplepaySessionRequest { +) -> RouterResult<payment_types::ApplepaySessionRequest> { + let initiative_context = session_token_data + .initiative_context + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get initiative_context for apple pay session call")?; + Ok(payment_types::ApplepaySessionRequest { merchant_identifier: session_token_data.merchant_identifier.clone(), display_name: session_token_data.display_name.clone(), - initiative: session_token_data.initiative.clone(), - initiative_context: session_token_data.initiative_context, - } + initiative: session_token_data.initiative.to_string(), + initiative_context, + }) } fn get_apple_pay_amount_info( @@ -461,7 +490,7 @@ fn create_apple_pay_session_response( response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::ApplePay(Box::new( payment_types::ApplepaySessionTokenResponse { - session_token_data: response, + session_token_data: Some(response), payment_request_data: apple_pay_payment_request, connector: connector_name, delayed_session_token: delayed_response, @@ -476,7 +505,18 @@ fn create_apple_pay_session_response( }), None => Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { - session_token: payment_types::SessionToken::NoSessionTokenReceived, + session_token: payment_types::SessionToken::ApplePay(Box::new( + payment_types::ApplepaySessionTokenResponse { + session_token_data: None, + payment_request_data: apple_pay_payment_request, + connector: connector_name, + delayed_session_token: delayed_response, + sdk_next_action: { payment_types::SdkNextAction { next_action } }, + connector_reference_id: None, + connector_sdk_public_key: None, + connector_merchant_id: None, + }, + )), }), ..router_data.clone() }), @@ -650,6 +690,7 @@ where _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, business_profile: &storage::business_profile::BusinessProfile, + header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self>; } @@ -698,13 +739,21 @@ impl RouterDataSession for types::PaymentsSessionRouterData { _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, business_profile: &storage::business_profile::BusinessProfile, + header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { match connector.get_token { api::GetToken::GpayMetadata => { create_gpay_session_token(state, self, connector, business_profile) } api::GetToken::ApplePayMetadata => { - create_applepay_session_token(state, self, connector, business_profile).await + create_applepay_session_token( + state, + self, + connector, + business_profile, + header_payload, + ) + .await } api::GetToken::PaypalSdkMetadata => { create_paypal_sdk_session_token(state, self, connector, business_profile) 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 7a876779033..07803a0c0fb 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -57,6 +57,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &storage::business_profile::BusinessProfile, + _header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::SetupMandate, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index c543be8cc92..f0d332514d1 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -77,6 +77,8 @@ pub mod headers { pub const X_CLIENT_SOURCE: &str = "X-Client-Source"; pub const X_PAYMENT_CONFIRM_SOURCE: &str = "X-Payment-Confirm-Source"; pub const CONTENT_LENGTH: &str = "Content-Length"; + pub const BROWSER_NAME: &str = "browsername"; + pub const X_CLIENT_PLATFORM: &str = "x-client-platform"; } pub mod pii { diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 912421f4650..84c7986dd8a 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -8,7 +8,7 @@ use actix_web::{web, Responder}; use api_models::payments::HeaderPayload; use error_stack::report; use masking::PeekInterface; -use router_env::{env, instrument, tracing, types, Flow}; +use router_env::{env, instrument, logger, tracing, types, Flow}; use super::app::ReqState; use crate::{ @@ -593,6 +593,14 @@ pub async fn payments_connector_session( let flow = Flow::PaymentsSessionToken; let payload = json_payload.into_inner(); + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { + Ok(headers) => headers, + Err(err) => { + logger::error!(?err, "Failed to get headers in payments_connector_session"); + HeaderPayload::default() + } + }; + tracing::Span::current().record("payment_id", &payload.payment_id); let locking_action = payload.get_locking_input(flow.clone()); @@ -619,7 +627,7 @@ pub async fn payments_connector_session( api::AuthFlow::Client, payments::CallConnectorAction::Trigger, None, - HeaderPayload::default(), + header_payload.clone(), ) }, &auth::PublishableKeyAuth, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index f754b31e0b0..57fc613af77 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -19,7 +19,10 @@ use masking::{ExposeInterface, PeekInterface}; use super::domain; use crate::{ core::errors, - headers::{X_CLIENT_SOURCE, X_CLIENT_VERSION, X_PAYMENT_CONFIRM_SOURCE}, + headers::{ + BROWSER_NAME, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, + X_PAYMENT_CONFIRM_SOURCE, + }, services::authentication::get_header_value_by_key, types::{ api::{self as api_types, routing as routing_types}, @@ -1106,11 +1109,32 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { let client_version = get_header_value_by_key(X_CLIENT_VERSION.into(), headers)?.map(|val| val.to_string()); + let browser_name_str = + get_header_value_by_key(BROWSER_NAME.into(), headers)?.map(|val| val.to_string()); + + let browser_name: Option<api_enums::BrowserName> = browser_name_str.map(|browser_name| { + browser_name + .parse_enum("BrowserName") + .unwrap_or(api_enums::BrowserName::Unknown) + }); + + let x_client_platform_str = + get_header_value_by_key(X_CLIENT_PLATFORM.into(), headers)?.map(|val| val.to_string()); + + let x_client_platform: Option<api_enums::ClientPlatform> = + x_client_platform_str.map(|x_client_platform| { + x_client_platform + .parse_enum("ClientPlatform") + .unwrap_or(api_enums::ClientPlatform::Unknown) + }); + Ok(Self { payment_confirm_source, client_source, client_version, x_hs_latency: Some(x_hs_latency), + browser_name, + x_client_platform, }) } } diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs index 590ad15d7f6..605f63d0f64 100644 --- a/crates/router/tests/connectors/payme.rs +++ b/crates/router/tests/connectors/payme.rs @@ -68,6 +68,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { return_url: None, connector_customer: None, payment_method_token: None, + #[cfg(feature = "payouts")] currency: None, #[cfg(feature = "payouts")] payout_method_data: None, diff --git a/crates/router/tests/connectors/square.rs b/crates/router/tests/connectors/square.rs index 322708c1da6..f7b633e8a15 100644 --- a/crates/router/tests/connectors/square.rs +++ b/crates/router/tests/connectors/square.rs @@ -47,6 +47,7 @@ fn get_default_payment_info(payment_method_token: Option<String>) -> Option<util payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, + #[cfg(feature = "payouts")] currency: None, }) } diff --git a/crates/router/tests/connectors/stax.rs b/crates/router/tests/connectors/stax.rs index 573bdd93802..f3d0f06ec1b 100644 --- a/crates/router/tests/connectors/stax.rs +++ b/crates/router/tests/connectors/stax.rs @@ -50,6 +50,7 @@ fn get_default_payment_info( payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, + #[cfg(feature = "payouts")] currency: None, }) } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index d1c3f40f388..ea7787a2c21 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -68,6 +68,7 @@ pub struct PaymentInfo { pub payment_method_token: Option<String>, #[cfg(feature = "payouts")] pub payout_method_data: Option<types::api::PayoutMethodData>, + #[cfg(feature = "payouts")] pub currency: Option<enums::Currency>, }
2024-06-26T14:53:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently, the Apple Pay session call is mandatory in all cases. This requirement also mandates configuring the initiative_context, which is the domain name where the Apple Pay payment is being processed. However, in the case of an iOS app, a domain is not required, so this field can be made optional. Additionally, in this case, the session call to Apple Pay can be skipped. On the web, Apple Pay is supported only in Safari. Therefore, the session call should be skipped in web environments when the browser is not Safari. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant connector account with apple pay manual flow. Below is the metadata for the manual flow. ``` "session_token_data": { "initiative": "web", "certificate": "==", "display_name": "applepay", "certificate_keys": "", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "", "payment_processing_certificate_key": "", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "", "merchant_business_country": "US" } ``` -> Currently we make session call only if `x_client_platform` and `browsername` header None or if it is web and Safari respectively. -> When mca is configured with write domain and header is not passed ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_7e0d9f48e20b430baa86eb956dc99142' \ --data '{ "payment_id": "pay_7WAejcRN248R0Y7Kwsfh", "wallets": [], "client_secret": "pay_7WAejcRN248R0Y7Kwsfh_secret_CDL03LbGwQQnMPVA0Lq0" }' ``` <img width="1135" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/2b02346c-0013-432b-be1e-72fd4769f4a4"> -> When mca is configured with write domain and header is passed as ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'browsername: Safari' \ --header 'x_client_platform: web' \ --header 'api-key: pk_dev_7e0d9f48e20b430baa86eb956dc99142' \ --data '{ "payment_id": "pay_7WAejcRN248R0Y7Kwsfh", "wallets": [], "client_secret": "pay_7WAejcRN248R0Y7Kwsfh_secret_CDL03LbGwQQnMPVA0Lq0" }' ``` <img width="1140" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e041b783-034a-46ca-a7f3-8c2c0ea03f07"> -> mac with write domain and wrong value in header ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'browsername: aa' \ --header 'x-client-platform: bb' \ --header 'api-key: pk_dev_7e0d9f48e20b430baa86eb956dc99142' \ --data '{ "payment_id": "pay_oisWpJs0i1gXIpdYMqFp", "wallets": [], "client_secret": "pay_oisWpJs0i1gXIpdYMqFp_secret_fkzm5bW5WR5wssQxEo3f" }' ``` <img width="1141" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/ce7416de-ec0b-4e5d-b863-bb62b84f2c36"> -> If only one header is passed ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-client-platform: ios' \ --header 'api-key: pk_dev_7e0d9f48e20b430baa86eb956dc99142' \ --data '{ "payment_id": "pay_oisWpJs0i1gXIpdYMqFp", "wallets": [], "client_secret": "pay_oisWpJs0i1gXIpdYMqFp_secret_fkzm5bW5WR5wssQxEo3f" }' ``` <img width="1145" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/babba52d-0ee2-4b5f-a989-ca4a7317c7d1"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9c49ded104b81f1aefcc288e3ded64ebbd4d466f
juspay/hyperswitch
juspay__hyperswitch-5127
Bug: feat: add endpoint for terminate auth select Add support to terminate auth select, - the api will take Auth Select SPT and - it will either SSO or TOTP SPT as per requested scenario
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 4f5651e0a3c..b357a3389d9 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -10,16 +10,17 @@ use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, }, - AcceptInviteFromEmailRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, - ConnectAccountRequest, CreateInternalUserRequest, CreateUserAuthenticationMethodRequest, - DashboardEntryResponse, ForgotPasswordRequest, GetSsoAuthUrlRequest, - GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, - GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest, - RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, - SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, - SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse, - UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, - UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse, + ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, + CreateUserAuthenticationMethodRequest, DashboardEntryResponse, ForgotPasswordRequest, + GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, + GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, + ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, + SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, + SsoSignInRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, + TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, + UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, + VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -83,7 +84,8 @@ common_utils::impl_misc_api_event_type!( CreateUserAuthenticationMethodRequest, UpdateUserAuthenticationMethodRequest, GetSsoAuthUrlRequest, - SsoSignInRequest + SsoSignInRequest, + AuthSelectRequest ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index b2ed491b677..02a4a09dc94 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -372,3 +372,8 @@ pub struct SsoSignInRequest { pub struct AuthIdQueryParam { pub auth_id: Option<String>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct AuthSelectRequest { + pub id: String, +} diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c4260a92948..3e9145c2d33 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2312,3 +2312,41 @@ pub async fn sso_sign( auth::cookies::set_cookie_response(response, token) } + +pub async fn terminate_auth_select( + state: SessionState, + user_token: auth::UserFromSinglePurposeToken, + req: user_api::AuthSelectRequest, +) -> UserResponse<user_api::TokenResponse> { + let user_from_db: domain::UserFromStorage = state + .global_store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let user_authentication_method = state + .store + .get_user_authentication_method_by_id(&req.id) + .await + .change_context(UserErrors::InternalServerError)?; + + let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; + let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; + + // Skip SSO if continue with password(TOTP) + if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) + && user_authentication_method.auth_type != common_enums::UserAuthType::OpenIdConnect + { + next_flow = next_flow.skip(user_from_db, &state).await?; + } + let token = next_flow.get_token(&state).await?; + + auth::cookies::set_cookie_response( + user_api::TokenResponse { + token: token.clone(), + token_type: next_flow.get_flow().into(), + }, + token, + ) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 80157c476b3..0cf7de4d33c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1417,7 +1417,8 @@ impl User { .service( web::resource("/list").route(web::get().to(list_user_authentication_methods)), ) - .service(web::resource("/url").route(web::get().to(get_sso_auth_url))), + .service(web::resource("/url").route(web::get().to(get_sso_auth_url))) + .service(web::resource("/select").route(web::post().to(terminate_auth_select))), ); #[cfg(feature = "email")] diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 115bcf6b9a0..03d12386918 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -232,7 +232,8 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateUserAuthenticationMethod | Flow::ListUserAuthenticationMethods | Flow::GetSsoAuthUrl - | Flow::SignInWithSso => Self::User, + | Flow::SignInWithSso + | Flow::AuthSelect => Self::User, Flow::ListRoles | Flow::GetRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index dae78d31bf0..7e55393cc57 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -876,3 +876,22 @@ pub async fn list_user_authentication_methods( )) .await } + +pub async fn terminate_auth_select( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::AuthSelectRequest>, +) -> HttpResponse { + let flow = Flow::AuthSelect; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, user, req, _| user_core::terminate_auth_select(state, user, req), + &auth::SinglePurposeJWTAuth(TokenPurpose::AuthSelect), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index ef73b88015f..97fb69074a6 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -51,9 +51,8 @@ impl SPTFlow { ) -> UserResult<bool> { match self { // Auth - // AuthSelect and SSO flow are not enabled, once the terminate SSO API is ready, we can enable these flows - Self::AuthSelect => Ok(false), - Self::SSO => Ok(false), + Self::AuthSelect => Ok(true), + Self::SSO => Ok(true), // TOTP Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)), // Main email APIs @@ -311,6 +310,26 @@ impl NextFlow { } } } + + pub async fn skip(self, user: UserFromStorage, state: &SessionState) -> UserResult<Self> { + let flows = self.origin.get_flows(); + let index = flows + .iter() + .position(|flow| flow == &self.get_flow()) + .ok_or(UserErrors::InternalServerError)?; + let remaining_flows = flows.iter().skip(index + 1); + for flow in remaining_flows { + if flow.is_required(&user, &self.path, state).await? { + return Ok(Self { + origin: self.origin.clone(), + next_flow: *flow, + user, + path: self.path, + }); + } + } + Err(UserErrors::InternalServerError.into()) + } } impl From<UserFlow> for TokenPurpose { diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 023cd2a7944..0b8f7f184da 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -155,7 +155,7 @@ pub enum Flow { PaymentsStart, /// Payments list flow. PaymentsList, - // Payments filters flow + /// Payments filters flow PaymentsFilters, #[cfg(feature = "payouts")] /// Payouts create flow @@ -412,7 +412,7 @@ pub enum Flow { UserFromEmail, /// Begin TOTP TotpBegin, - // Reset TOTP + /// Reset TOTP TotpReset, /// Verify TOTP TotpVerify, @@ -422,20 +422,22 @@ pub enum Flow { RecoveryCodeVerify, /// Generate or Regenerate recovery codes RecoveryCodesGenerate, - // Terminate two factor authentication + /// Terminate two factor authentication TerminateTwoFactorAuth, - // Check 2FA status + /// Check 2FA status TwoFactorAuthStatus, - // Create user authentication method + /// Create user authentication method CreateUserAuthenticationMethod, - // Update user authentication method + /// Update user authentication method UpdateUserAuthenticationMethod, - // List user authentication methods + /// List user authentication methods ListUserAuthenticationMethods, /// Get sso auth url GetSsoAuthUrl, /// Signin with SSO SignInWithSso, + /// Auth Select + AuthSelect, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event
2024-06-26T14:13:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Add endpoint `/auth/select` to terminate auth select - The api will take Auth Select SPT and will give SSO SPT or TOTP SPT based on the choice selected - SSO SPT if user selects continue with SSO - TOTP SPT if user selects continue with TOTP ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes #5127 ## How did you test it? If request from id that has auth type as `open_id_connect`: ``` curl --location 'http://localhost:8080/user/auth/select' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT' \ --header 'Cookie: Cookie_1=value' \ --data '{ "id":"f20742d2-f1b8-4dad-8b2d-cf8fe6d457eb" }' ``` response will contain token type as `sso` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6InNzbyIsIm9yaWdpbiI6ImFjY2VwdF9pbnZpdGF0aW9uX2Zyb21fZW1haWwiLCJwYXRoIjpbImF1dGhfc2VsZWN0Il0sImV4cCI6MTcxOTU4NDc2NX0.ChD9An8L4szVjLn9Q51otVOXOuZf8kdgRMmH865lQQI", "token_type": "sso" } ``` If request from id other than `open_id_connect` ``` curl --location 'http://localhost:8080/user/auth/select' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT' \ --header 'Cookie: Cookie_1=value' \ --data '{ "id":"65ff02eb-f3dc-4afc-b8ac-cef2a30c4d12" }' ``` Response will contain token type as `totp` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjJkNjMxZDUtMGQzMi00Y2IxLTg2MTQtNWVlNWI2MDczYTVkIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJhY2NlcHRfaW52aXRhdGlvbl9mcm9tX2VtYWlsIiwicGF0aCI6WyJhdXRoX3NlbGVjdCJdLCJleHAiOjE3MTk1ODQ5MDl9.hEBp49fycxiSW1VoyPR6s9TISO4lQKP3ta0S4SH3C9s", "token_type": "totp" } ``` Db entries for correponding request ids: ![Screenshot 2024-06-26 at 7 59 41 PM](https://github.com/juspay/hyperswitch/assets/64925866/0634150a-91c8-4cfa-bfe3-3412eba7f151) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ce7d0d427d817eb4199f2f6ea8ea86a04bd98a26
juspay/hyperswitch
juspay__hyperswitch-5148
Bug: feat(analytics): Add v2 payment analytics Add analytics based on the payment intent since merchants rely on payment intents this would help more closely relate to the merchant facing data. Currently this will support 4 metrics - successful smart retries - total smart retries - smart retried amount - payment intent count filters - status - currency group by - status - currency
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index ab47397b8af..b455e79b253 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -10,6 +10,7 @@ use super::{ active_payments::metrics::ActivePaymentsMetricRow, auth_events::metrics::AuthEventMetricRow, health_check::HealthCheck, + payment_intents::{filters::PaymentIntentFilterRow, metrics::PaymentIntentMetricRow}, payments::{ distribution::PaymentDistributionRow, filters::FilterRow, metrics::PaymentMetricRow, }, @@ -157,6 +158,8 @@ where impl super::payments::filters::PaymentFilterAnalytics for ClickhouseClient {} impl super::payments::metrics::PaymentMetricAnalytics for ClickhouseClient {} impl super::payments::distribution::PaymentDistributionAnalytics for ClickhouseClient {} +impl super::payment_intents::filters::PaymentIntentFilterAnalytics for ClickhouseClient {} +impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {} impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {} impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {} impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {} @@ -247,6 +250,26 @@ impl TryInto<FilterRow> for serde_json::Value { } } +impl TryInto<PaymentIntentMetricRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<PaymentIntentMetricRow, Self::Error> { + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse PaymentIntentMetricRow in clickhouse results", + )) + } +} + +impl TryInto<PaymentIntentFilterRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<PaymentIntentFilterRow, Self::Error> { + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse PaymentIntentFilterRow in clickhouse results", + )) + } +} + impl TryInto<RefundMetricRow> for serde_json::Value { type Error = Report<ParsingError>; diff --git a/crates/analytics/src/core.rs b/crates/analytics/src/core.rs index f3278349748..2c5945f75b5 100644 --- a/crates/analytics/src/core.rs +++ b/crates/analytics/src/core.rs @@ -11,6 +11,11 @@ pub async fn get_domain_info( download_dimensions: None, dimensions: utils::get_payment_dimensions(), }, + AnalyticsDomain::PaymentIntents => GetInfoResponse { + metrics: utils::get_payment_intent_metrics_info(), + download_dimensions: None, + dimensions: utils::get_payment_intent_dimensions(), + }, AnalyticsDomain::Refunds => GetInfoResponse { metrics: utils::get_refund_metrics_info(), download_dimensions: None, diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index d3db03a6977..10e628475e8 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -3,6 +3,7 @@ pub mod core; pub mod disputes; pub mod errors; pub mod metrics; +pub mod payment_intents; pub mod payments; mod query; pub mod refunds; @@ -39,6 +40,10 @@ use api_models::analytics::{ }, auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier}, disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier}, + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetrics, + PaymentIntentMetricsBucketIdentifier, + }, payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier}, refunds::{RefundDimensions, RefundFilters, RefundMetrics, RefundMetricsBucketIdentifier}, sdk_events::{ @@ -60,6 +65,7 @@ use strum::Display; use self::{ active_payments::metrics::{ActivePaymentsMetric, ActivePaymentsMetricRow}, auth_events::metrics::{AuthEventMetric, AuthEventMetricRow}, + payment_intents::metrics::{PaymentIntentMetric, PaymentIntentMetricRow}, payments::{ distribution::{PaymentDistribution, PaymentDistributionRow}, metrics::{PaymentMetric, PaymentMetricRow}, @@ -313,6 +319,111 @@ impl AnalyticsProvider { .await } + pub async fn get_payment_intent_metrics( + &self, + metric: &PaymentIntentMetrics, + dimensions: &[PaymentIntentDimensions], + merchant_id: &str, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + ) -> types::MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + // Metrics to get the fetch time for each payment intent metric + metrics::request::record_operation_time( + async { + match self { + Self::Sqlx(pool) => { + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::Clickhouse(pool) => { + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::CombinedCkh(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!(metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + sqlx_pool, + )); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics metrics") + }, + _ => {} + + }; + + ckh_result + } + Self::CombinedSqlx(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!(metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + sqlx_pool, + )); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics metrics") + }, + _ => {} + + }; + + sqlx_result + } + } + }, + &metrics::METRIC_FETCH_TIME, + metric, + self, + ) + .await + } + pub async fn get_refund_metrics( &self, metric: &RefundMetrics, @@ -756,11 +867,13 @@ pub struct ReportConfig { pub enum AnalyticsFlow { GetInfo, GetPaymentMetrics, + GetPaymentIntentMetrics, GetRefundsMetrics, GetSdkMetrics, GetAuthMetrics, GetActivePaymentsMetrics, GetPaymentFilters, + GetPaymentIntentFilters, GetRefundFilters, GetSdkEventFilters, GetApiEvents, diff --git a/crates/analytics/src/payment_intents.rs b/crates/analytics/src/payment_intents.rs new file mode 100644 index 00000000000..449dd94788c --- /dev/null +++ b/crates/analytics/src/payment_intents.rs @@ -0,0 +1,13 @@ +pub mod accumulator; +mod core; +pub mod filters; +pub mod metrics; +pub mod types; +pub use accumulator::{PaymentIntentMetricAccumulator, PaymentIntentMetricsAccumulator}; + +pub trait PaymentIntentAnalytics: + metrics::PaymentIntentMetricAnalytics + filters::PaymentIntentFilterAnalytics +{ +} + +pub use self::core::{get_filters, get_metrics}; diff --git a/crates/analytics/src/payment_intents/accumulator.rs b/crates/analytics/src/payment_intents/accumulator.rs new file mode 100644 index 00000000000..8fd98a1e73c --- /dev/null +++ b/crates/analytics/src/payment_intents/accumulator.rs @@ -0,0 +1,90 @@ +use api_models::analytics::payment_intents::PaymentIntentMetricsBucketValue; +use bigdecimal::ToPrimitive; + +use super::metrics::PaymentIntentMetricRow; + +#[derive(Debug, Default)] +pub struct PaymentIntentMetricsAccumulator { + pub successful_smart_retries: CountAccumulator, + pub total_smart_retries: CountAccumulator, + pub smart_retried_amount: SumAccumulator, + pub payment_intent_count: CountAccumulator, +} + +#[derive(Debug, Default)] +pub struct ErrorDistributionRow { + pub count: i64, + pub total: i64, + pub error_message: String, +} + +#[derive(Debug, Default)] +pub struct ErrorDistributionAccumulator { + pub error_vec: Vec<ErrorDistributionRow>, +} + +#[derive(Debug, Default)] +#[repr(transparent)] +pub struct CountAccumulator { + pub count: Option<i64>, +} + +pub trait PaymentIntentMetricAccumulator { + type MetricOutput; + + fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow); + + fn collect(self) -> Self::MetricOutput; +} + +#[derive(Debug, Default)] +#[repr(transparent)] +pub struct SumAccumulator { + pub total: Option<i64>, +} + +impl PaymentIntentMetricAccumulator for CountAccumulator { + type MetricOutput = Option<u64>; + #[inline] + fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) { + self.count = match (self.count, metrics.count) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + } + } + #[inline] + fn collect(self) -> Self::MetricOutput { + self.count.and_then(|i| u64::try_from(i).ok()) + } +} + +impl PaymentIntentMetricAccumulator for SumAccumulator { + type MetricOutput = Option<u64>; + #[inline] + fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) { + self.total = match ( + self.total, + metrics.total.as_ref().and_then(ToPrimitive::to_i64), + ) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + } + } + #[inline] + fn collect(self) -> Self::MetricOutput { + self.total.and_then(|i| u64::try_from(i).ok()) + } +} + +impl PaymentIntentMetricsAccumulator { + pub fn collect(self) -> PaymentIntentMetricsBucketValue { + PaymentIntentMetricsBucketValue { + successful_smart_retries: self.successful_smart_retries.collect(), + total_smart_retries: self.total_smart_retries.collect(), + smart_retried_amount: self.smart_retried_amount.collect(), + payment_intent_count: self.payment_intent_count.collect(), + } + } +} diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs new file mode 100644 index 00000000000..e3932baaf07 --- /dev/null +++ b/crates/analytics/src/payment_intents/core.rs @@ -0,0 +1,226 @@ +#![allow(dead_code)] +use std::collections::HashMap; + +use api_models::analytics::{ + payment_intents::{ + MetricsBucketResponse, PaymentIntentDimensions, PaymentIntentMetrics, + PaymentIntentMetricsBucketIdentifier, + }, + AnalyticsMetadata, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, + MetricsResponse, PaymentIntentFilterValue, PaymentIntentFiltersResponse, +}; +use common_utils::errors::CustomResult; +use error_stack::ResultExt; +use router_env::{ + instrument, logger, + metrics::add_attributes, + tracing::{self, Instrument}, +}; + +use super::{ + filters::{get_payment_intent_filter_for_dimension, PaymentIntentFilterRow}, + metrics::PaymentIntentMetricRow, + PaymentIntentMetricsAccumulator, +}; +use crate::{ + errors::{AnalyticsError, AnalyticsResult}, + metrics, + payment_intents::PaymentIntentMetricAccumulator, + AnalyticsProvider, +}; + +#[derive(Debug)] +pub enum TaskType { + MetricTask( + PaymentIntentMetrics, + CustomResult< + Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + AnalyticsError, + >, + ), +} + +#[instrument(skip_all)] +pub async fn get_metrics( + pool: &AnalyticsProvider, + merchant_id: &str, + req: GetPaymentIntentMetricRequest, +) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { + let mut metrics_accumulator: HashMap< + PaymentIntentMetricsBucketIdentifier, + PaymentIntentMetricsAccumulator, + > = HashMap::new(); + + let mut set = tokio::task::JoinSet::new(); + for metric_type in req.metrics.iter().cloned() { + let req = req.clone(); + let pool = pool.clone(); + let task_span = tracing::debug_span!( + "analytics_payment_intents_metrics_query", + payment_metric = metric_type.as_ref() + ); + + // TODO: lifetime issues with joinset, + // can be optimized away if joinset lifetime requirements are relaxed + let merchant_id_scoped = merchant_id.to_owned(); + set.spawn( + async move { + let data = pool + .get_payment_intent_metrics( + &metric_type, + &req.group_by_names.clone(), + &merchant_id_scoped, + &req.filters, + &req.time_series.map(|t| t.granularity), + &req.time_range, + ) + .await + .change_context(AnalyticsError::UnknownError); + TaskType::MetricTask(metric_type, data) + } + .instrument(task_span), + ); + } + + while let Some(task_type) = set + .join_next() + .await + .transpose() + .change_context(AnalyticsError::UnknownError)? + { + match task_type { + TaskType::MetricTask(metric, data) => { + let data = data?; + let attributes = &add_attributes([ + ("metric_type", metric.to_string()), + ("source", pool.to_string()), + ]); + + let value = u64::try_from(data.len()); + if let Ok(val) = value { + metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes); + logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); + } + + for (id, value) in data { + logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); + let metrics_builder = metrics_accumulator.entry(id).or_default(); + match metric { + PaymentIntentMetrics::SuccessfulSmartRetries => metrics_builder + .successful_smart_retries + .add_metrics_bucket(&value), + PaymentIntentMetrics::TotalSmartRetries => metrics_builder + .total_smart_retries + .add_metrics_bucket(&value), + PaymentIntentMetrics::SmartRetriedAmount => metrics_builder + .smart_retried_amount + .add_metrics_bucket(&value), + PaymentIntentMetrics::PaymentIntentCount => metrics_builder + .payment_intent_count + .add_metrics_bucket(&value), + } + } + + logger::debug!( + "Analytics Accumulated Results: metric: {}, results: {:#?}", + metric, + metrics_accumulator + ); + } + } + } + + let query_data: Vec<MetricsBucketResponse> = metrics_accumulator + .into_iter() + .map(|(id, val)| MetricsBucketResponse { + values: val.collect(), + dimensions: id, + }) + .collect(); + + Ok(MetricsResponse { + query_data, + meta_data: [AnalyticsMetadata { + current_time_range: req.time_range, + }], + }) +} + +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetPaymentIntentFiltersRequest, + merchant_id: &String, +) -> AnalyticsResult<PaymentIntentFiltersResponse> { + let mut res = PaymentIntentFiltersResponse::default(); + + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(pool) => { + get_payment_intent_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + } + AnalyticsProvider::Clickhouse(pool) => { + get_payment_intent_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + } + AnalyticsProvider::CombinedCkh(sqlx_poll, ckh_pool) => { + let ckh_result = get_payment_intent_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_payment_intent_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_poll, + ) + .await; + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics filters") + }, + _ => {} + }; + ckh_result + } + AnalyticsProvider::CombinedSqlx(sqlx_poll, ckh_pool) => { + let ckh_result = get_payment_intent_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_payment_intent_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_poll, + ) + .await; + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics filters") + }, + _ => {} + }; + sqlx_result + } + } + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: PaymentIntentFilterRow| match dim { + PaymentIntentDimensions::PaymentIntentStatus => fil.status.map(|i| i.as_ref().to_string()), + PaymentIntentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), + }) + .collect::<Vec<String>>(); + res.query_data.push(PaymentIntentFilterValue { + dimension: dim, + values, + }) + } + Ok(res) +} diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs new file mode 100644 index 00000000000..1a74cfd510e --- /dev/null +++ b/crates/analytics/src/payment_intents/filters.rs @@ -0,0 +1,56 @@ +use api_models::analytics::{payment_intents::PaymentIntentDimensions, Granularity, TimeRange}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums::{Currency, IntentStatus}; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{ + AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, + LoadRow, + }, +}; + +pub trait PaymentIntentFilterAnalytics: LoadRow<PaymentIntentFilterRow> {} + +pub async fn get_payment_intent_filter_for_dimension<T>( + dimension: PaymentIntentDimensions, + merchant: &String, + time_range: &TimeRange, + pool: &T, +) -> FiltersResult<Vec<PaymentIntentFilterRow>> +where + T: AnalyticsDataSource + PaymentIntentFilterAnalytics, + 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::PaymentIntent); + + query_builder.add_select_column(dimension).switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant) + .switch()?; + + query_builder.set_distinct(); + + query_builder + .execute_query::<PaymentIntentFilterRow, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] +pub struct PaymentIntentFilterRow { + pub status: Option<DBEnumWrapper<IntentStatus>>, + pub currency: Option<DBEnumWrapper<Currency>>, +} diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs new file mode 100644 index 00000000000..3a0cbbc85db --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics.rs @@ -0,0 +1,126 @@ +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetrics, + PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use diesel_models::enums as storage_enums; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, +}; + +mod payment_intent_count; +mod smart_retried_amount; +mod successful_smart_retries; +mod total_smart_retries; + +use payment_intent_count::PaymentIntentCount; +use smart_retried_amount::SmartRetriedAmount; +use successful_smart_retries::SuccessfulSmartRetries; +use total_smart_retries::TotalSmartRetries; + +#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +pub struct PaymentIntentMetricRow { + pub status: Option<DBEnumWrapper<storage_enums::IntentStatus>>, + pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, + pub total: Option<bigdecimal::BigDecimal>, + pub count: Option<i64>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub start_bucket: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub end_bucket: Option<PrimitiveDateTime>, +} + +pub trait PaymentIntentMetricAnalytics: LoadRow<PaymentIntentMetricRow> {} + +#[async_trait::async_trait] +pub trait PaymentIntentMetric<T> +where + T: AnalyticsDataSource + PaymentIntentMetricAnalytics, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + merchant_id: &str, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>; +} + +#[async_trait::async_trait] +impl<T> PaymentIntentMetric<T> for PaymentIntentMetrics +where + T: AnalyticsDataSource + PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + merchant_id: &str, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + match self { + Self::SuccessfulSmartRetries => { + SuccessfulSmartRetries + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::TotalSmartRetries => { + TotalSmartRetries + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::SmartRetriedAmount => { + SmartRetriedAmount + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::PaymentIntentCount => { + PaymentIntentCount + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + } + } +} diff --git a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs new file mode 100644 index 00000000000..0f235375c4f --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs @@ -0,0 +1,121 @@ +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentIntentCount; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for PaymentIntentCount +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + merchant_id: &str, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntent); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + i.status.as_ref().map(|i| i.0), + i.currency.as_ref().map(|i| i.0), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs new file mode 100644 index 00000000000..470a0e66867 --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -0,0 +1,131 @@ +use api_models::{ + analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, + }, + enums::IntentStatus, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct SmartRetriedAmount; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for SmartRetriedAmount +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + merchant_id: &str, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntent); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Sum { + field: "amount", + alias: Some("total"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + query_builder + .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) + .switch()?; + query_builder + .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + i.status.as_ref().map(|i| i.0), + i.currency.as_ref().map(|i| i.0), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs new file mode 100644 index 00000000000..292062d1e10 --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs @@ -0,0 +1,130 @@ +use api_models::{ + analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, + }, + enums::IntentStatus, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct SuccessfulSmartRetries; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for SuccessfulSmartRetries +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + merchant_id: &str, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntent); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + query_builder + .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) + .switch()?; + query_builder + .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + i.status.as_ref().map(|i| i.0), + i.currency.as_ref().map(|i| i.0), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs new file mode 100644 index 00000000000..d5a3d142baf --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs @@ -0,0 +1,125 @@ +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct TotalSmartRetries; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for TotalSmartRetries +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + merchant_id: &str, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntent); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + query_builder + .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + i.status.as_ref().map(|i| i.0), + i.currency.as_ref().map(|i| i.0), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/types.rs b/crates/analytics/src/payment_intents/types.rs new file mode 100644 index 00000000000..9b1e7b8674d --- /dev/null +++ b/crates/analytics/src/payment_intents/types.rs @@ -0,0 +1,30 @@ +use api_models::analytics::payment_intents::{PaymentIntentDimensions, PaymentIntentFilters}; +use error_stack::ResultExt; + +use crate::{ + query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, + types::{AnalyticsCollection, AnalyticsDataSource}, +}; + +impl<T> QueryFilter<T> for PaymentIntentFilters +where + T: AnalyticsDataSource, + AnalyticsCollection: ToSql<T>, +{ + fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { + if !self.status.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::PaymentIntentStatus, + &self.status, + ) + .attach_printable("Error adding payment intent status filter")?; + } + if !self.currency.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::Currency, &self.currency) + .attach_printable("Error adding currency filter")?; + } + Ok(()) + } +} diff --git a/crates/analytics/src/payments/metrics/retries_count.rs b/crates/analytics/src/payments/metrics/retries_count.rs index 87d80c87fb4..3c4580d37a7 100644 --- a/crates/analytics/src/payments/metrics/retries_count.rs +++ b/crates/analytics/src/payments/metrics/retries_count.rs @@ -1,6 +1,9 @@ -use api_models::analytics::{ - payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, - Granularity, TimeRange, +use api_models::{ + analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, + }, + enums::IntentStatus, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -70,7 +73,7 @@ where .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) .switch()?; query_builder - .add_custom_filter_clause("status", "succeeded", FilterTypes::Equal) + .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal) .switch()?; time_range .set_filter_clause(&mut query_builder) diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index 2fda8fc57cd..a257fedc09d 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -6,14 +6,15 @@ use api_models::{ api_event::ApiEventDimensions, auth_events::AuthEventFlows, disputes::DisputeDimensions, + payment_intents::PaymentIntentDimensions, payments::{PaymentDimensions, PaymentDistributions}, refunds::{RefundDimensions, RefundType}, sdk_events::{SdkEventDimensions, SdkEventNames}, Granularity, }, enums::{ - AttemptStatus, AuthenticationType, Connector, Currency, DisputeStage, PaymentMethod, - PaymentMethodType, + AttemptStatus, AuthenticationType, Connector, Currency, DisputeStage, IntentStatus, + PaymentMethod, PaymentMethodType, }, refunds::RefundStatus, }; @@ -369,8 +370,10 @@ impl_to_sql_for_to_string!( String, &str, &PaymentDimensions, + &PaymentIntentDimensions, &RefundDimensions, PaymentDimensions, + PaymentIntentDimensions, &PaymentDistributions, RefundDimensions, PaymentMethod, @@ -378,6 +381,7 @@ impl_to_sql_for_to_string!( AuthenticationType, Connector, AttemptStatus, + IntentStatus, RefundStatus, storage_enums::RefundStatus, Currency, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 76ad9c254be..6a4faf50eb8 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -9,7 +9,7 @@ use common_utils::{ DbConnectionParams, }; use diesel_models::enums::{ - AttemptStatus, AuthenticationType, Currency, PaymentMethod, RefundStatus, + AttemptStatus, AuthenticationType, Currency, IntentStatus, PaymentMethod, RefundStatus, }; use error_stack::ResultExt; use sqlx::{ @@ -87,6 +87,7 @@ macro_rules! db_type { db_type!(Currency); db_type!(AuthenticationType); db_type!(AttemptStatus); +db_type!(IntentStatus); db_type!(PaymentMethod, TEXT); db_type!(RefundStatus); db_type!(RefundType); @@ -143,6 +144,8 @@ where impl super::payments::filters::PaymentFilterAnalytics for SqlxClient {} impl super::payments::metrics::PaymentMetricAnalytics for SqlxClient {} impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient {} +impl super::payment_intents::filters::PaymentIntentFilterAnalytics for SqlxClient {} +impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for SqlxClient {} impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {} impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {} impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {} @@ -429,6 +432,60 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::FilterRow { } } +impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMetricRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let status: Option<DBEnumWrapper<IntentStatus>> = + row.try_get("status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let currency: Option<DBEnumWrapper<Currency>> = + row.try_get("currency").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let count: Option<i64> = row.try_get("count").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + // Removing millisecond precision to get accurate diffs against clickhouse + let start_bucket: Option<PrimitiveDateTime> = row + .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? + .and_then(|dt| dt.replace_millisecond(0).ok()); + let end_bucket: Option<PrimitiveDateTime> = row + .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? + .and_then(|dt| dt.replace_millisecond(0).ok()); + Ok(Self { + status, + currency, + total, + count, + start_bucket, + end_bucket, + }) + } +} + +impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFilterRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let status: Option<DBEnumWrapper<IntentStatus>> = + row.try_get("status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let currency: Option<DBEnumWrapper<Currency>> = + row.try_get("currency").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + Ok(Self { status, currency }) + } +} + impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 5370fbc25ac..816c77fd304 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -15,6 +15,7 @@ use crate::errors::AnalyticsError; pub enum AnalyticsDomain { Payments, Refunds, + PaymentIntents, AuthEvents, SdkEvents, ApiEvents, diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index 0afe9bd6c5e..3955a8c1dfe 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -2,6 +2,7 @@ use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventMetrics}, auth_events::AuthEventMetrics, disputes::{DisputeDimensions, DisputeMetrics}, + payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, @@ -13,6 +14,10 @@ pub fn get_payment_dimensions() -> Vec<NameDescription> { PaymentDimensions::iter().map(Into::into).collect() } +pub fn get_payment_intent_dimensions() -> Vec<NameDescription> { + PaymentIntentDimensions::iter().map(Into::into).collect() +} + pub fn get_refund_dimensions() -> Vec<NameDescription> { RefundDimensions::iter().map(Into::into).collect() } @@ -29,6 +34,10 @@ pub fn get_payment_metrics_info() -> Vec<NameDescription> { PaymentMetrics::iter().map(Into::into).collect() } +pub fn get_payment_intent_metrics_info() -> Vec<NameDescription> { + PaymentIntentMetrics::iter().map(Into::into).collect() +} + pub fn get_refund_metrics_info() -> Vec<NameDescription> { RefundMetrics::iter().map(Into::into).collect() } diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 491420cfc02..85a9c3ded09 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -8,6 +8,7 @@ use self::{ api_event::{ApiEventDimensions, ApiEventMetrics}, auth_events::AuthEventMetrics, disputes::{DisputeDimensions, DisputeMetrics}, + payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, @@ -20,6 +21,7 @@ pub mod auth_events; pub mod connector_events; pub mod disputes; pub mod outgoing_webhook_event; +pub mod payment_intents; pub mod payments; pub mod refunds; pub mod sdk_events; @@ -114,6 +116,20 @@ pub struct GenerateReportRequest { pub email: Secret<String, EmailStrategy>, } +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetPaymentIntentMetricRequest { + pub time_series: Option<TimeSeries>, + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<PaymentIntentDimensions>, + #[serde(default)] + pub filters: payment_intents::PaymentIntentFilters, + pub metrics: HashSet<PaymentIntentMetrics>, + #[serde(default)] + pub delta: bool, +} + #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetRefundMetricRequest { @@ -187,6 +203,27 @@ pub struct FilterValue { pub values: Vec<String>, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetPaymentIntentFiltersRequest { + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<PaymentIntentDimensions>, +} + +#[derive(Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentIntentFiltersResponse { + pub query_data: Vec<PaymentIntentFilterValue>, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentIntentFilterValue { + pub dimension: PaymentIntentDimensions, + pub values: Vec<String>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs new file mode 100644 index 00000000000..232c1719047 --- /dev/null +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -0,0 +1,151 @@ +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, +}; + +use super::{NameDescription, TimeRange}; +use crate::enums::{Currency, IntentStatus}; + +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct PaymentIntentFilters { + #[serde(default)] + pub status: Vec<IntentStatus>, + pub currency: Vec<Currency>, +} + +#[derive( + Debug, + serde::Serialize, + serde::Deserialize, + strum::AsRefStr, + PartialEq, + PartialOrd, + Eq, + Ord, + strum::Display, + strum::EnumIter, + Clone, + Copy, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum PaymentIntentDimensions { + #[strum(serialize = "status")] + #[serde(rename = "status")] + PaymentIntentStatus, + Currency, +} + +#[derive( + Clone, + Debug, + Hash, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumIter, + strum::AsRefStr, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum PaymentIntentMetrics { + SuccessfulSmartRetries, + TotalSmartRetries, + SmartRetriedAmount, + PaymentIntentCount, +} + +#[derive(Debug, Default, serde::Serialize)] +pub struct ErrorResult { + pub reason: String, + pub count: i64, + pub percentage: f64, +} + +pub mod metric_behaviour { + pub struct SuccessfulSmartRetries; + pub struct TotalSmartRetries; + pub struct SmartRetriedAmount; + pub struct PaymentIntentCount; +} + +impl From<PaymentIntentMetrics> for NameDescription { + fn from(value: PaymentIntentMetrics) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + +impl From<PaymentIntentDimensions> for NameDescription { + fn from(value: PaymentIntentDimensions) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + +#[derive(Debug, serde::Serialize, Eq)] +pub struct PaymentIntentMetricsBucketIdentifier { + pub status: Option<IntentStatus>, + pub currency: Option<Currency>, + #[serde(rename = "time_range")] + pub time_bucket: TimeRange, + #[serde(rename = "time_bucket")] + #[serde(with = "common_utils::custom_serde::iso8601custom")] + pub start_time: time::PrimitiveDateTime, +} + +impl PaymentIntentMetricsBucketIdentifier { + #[allow(clippy::too_many_arguments)] + pub fn new( + status: Option<IntentStatus>, + currency: Option<Currency>, + normalized_time_range: TimeRange, + ) -> Self { + Self { + status, + currency, + time_bucket: normalized_time_range, + start_time: normalized_time_range.start_time, + } + } +} + +impl Hash for PaymentIntentMetricsBucketIdentifier { + fn hash<H: Hasher>(&self, state: &mut H) { + self.status.map(|i| i.to_string()).hash(state); + self.currency.hash(state); + self.time_bucket.hash(state); + } +} + +impl PartialEq for PaymentIntentMetricsBucketIdentifier { + fn eq(&self, other: &Self) -> bool { + let mut left = DefaultHasher::new(); + self.hash(&mut left); + let mut right = DefaultHasher::new(); + other.hash(&mut right); + left.finish() == right.finish() + } +} + +#[derive(Debug, serde::Serialize)] +pub struct PaymentIntentMetricsBucketValue { + pub successful_smart_retries: Option<u64>, + pub total_smart_retries: Option<u64>, + pub smart_retried_amount: Option<u64>, + pub payment_intent_count: Option<u64>, +} + +#[derive(Debug, serde::Serialize)] +pub struct MetricsBucketResponse { + #[serde(flatten)] + pub values: PaymentIntentMetricsBucketValue, + #[serde(flatten)] + pub dimensions: PaymentIntentMetricsBucketIdentifier, +} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index bed46f01f19..346fc06f20a 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -38,6 +38,24 @@ use crate::{ impl ApiEventMetric for TimeRange {} +impl ApiEventMetric for GetPaymentIntentFiltersRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Analytics) + } +} + +impl ApiEventMetric for GetPaymentIntentMetricRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Analytics) + } +} + +impl ApiEventMetric for PaymentIntentFiltersResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Analytics) + } +} + impl_misc_api_event_type!( PaymentMethodId, PaymentsSessionResponse, diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 0ef8a6a8bfc..3e3a0da4cab 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -65,6 +65,7 @@ pub enum ApiEventsType { Poll { poll_id: String, }, + Analytics, } impl ApiEventMetric for serde_json::Value {} diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 8d8910f7b2c..64f62f48762 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -14,8 +14,9 @@ pub mod routes { }, GenerateReportRequest, GetActivePaymentsMetricRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventMetricRequest, GetDisputeMetricRequest, - GetPaymentFiltersRequest, GetPaymentMetricRequest, GetRefundFilterRequest, - GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, + GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, + GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest, + GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, }; use error_stack::ResultExt; @@ -37,86 +38,105 @@ pub mod routes { impl Analytics { pub fn server(state: AppState) -> Scope { - let mut route = web::scope("/analytics/v1").app_data(web::Data::new(state)); - { - route = route - .service( - web::resource("metrics/payments") - .route(web::post().to(get_payment_metrics)), - ) - .service( - web::resource("metrics/refunds").route(web::post().to(get_refunds_metrics)), - ) - .service( - web::resource("filters/payments") - .route(web::post().to(get_payment_filters)), - ) - .service( - web::resource("filters/refunds").route(web::post().to(get_refund_filters)), - ) - .service(web::resource("{domain}/info").route(web::get().to(get_info))) - .service( - web::resource("report/dispute") - .route(web::post().to(generate_dispute_report)), - ) - .service( - web::resource("report/refunds") - .route(web::post().to(generate_refund_report)), - ) - .service( - web::resource("report/payments") - .route(web::post().to(generate_payment_report)), - ) - .service( - web::resource("metrics/sdk_events") - .route(web::post().to(get_sdk_event_metrics)), - ) - .service( - web::resource("metrics/active_payments") - .route(web::post().to(get_active_payments_metrics)), - ) - .service( - web::resource("filters/sdk_events") - .route(web::post().to(get_sdk_event_filters)), - ) - .service( - web::resource("metrics/auth_events") - .route(web::post().to(get_auth_event_metrics)), - ) - .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)), - ) - .service( - web::resource("filters/api_events") - .route(web::post().to(get_api_event_filters)), - ) - .service( - web::resource("metrics/api_events") - .route(web::post().to(get_api_events_metrics)), - ) - .service( - web::resource("search").route(web::post().to(get_global_search_results)), - ) - .service( - web::resource("search/{domain}").route(web::post().to(get_search_results)), - ) - .service( - web::resource("filters/disputes") - .route(web::post().to(get_dispute_filters)), - ) - .service( - web::resource("metrics/disputes") - .route(web::post().to(get_dispute_metrics)), - ) - } - route + web::scope("/analytics") + .app_data(web::Data::new(state)) + .service( + web::scope("/v1") + .service( + web::resource("metrics/payments") + .route(web::post().to(get_payment_metrics)), + ) + .service( + web::resource("metrics/refunds") + .route(web::post().to(get_refunds_metrics)), + ) + .service( + web::resource("filters/payments") + .route(web::post().to(get_payment_filters)), + ) + .service( + web::resource("filters/refunds") + .route(web::post().to(get_refund_filters)), + ) + .service(web::resource("{domain}/info").route(web::get().to(get_info))) + .service( + web::resource("report/dispute") + .route(web::post().to(generate_dispute_report)), + ) + .service( + web::resource("report/refunds") + .route(web::post().to(generate_refund_report)), + ) + .service( + web::resource("report/payments") + .route(web::post().to(generate_payment_report)), + ) + .service( + web::resource("metrics/sdk_events") + .route(web::post().to(get_sdk_event_metrics)), + ) + .service( + web::resource("metrics/active_payments") + .route(web::post().to(get_active_payments_metrics)), + ) + .service( + web::resource("filters/sdk_events") + .route(web::post().to(get_sdk_event_filters)), + ) + .service( + web::resource("metrics/auth_events") + .route(web::post().to(get_auth_event_metrics)), + ) + .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)), + ) + .service( + web::resource("filters/api_events") + .route(web::post().to(get_api_event_filters)), + ) + .service( + web::resource("metrics/api_events") + .route(web::post().to(get_api_events_metrics)), + ) + .service( + web::resource("search") + .route(web::post().to(get_global_search_results)), + ) + .service( + web::resource("search/{domain}") + .route(web::post().to(get_search_results)), + ) + .service( + web::resource("filters/disputes") + .route(web::post().to(get_dispute_filters)), + ) + .service( + web::resource("metrics/disputes") + .route(web::post().to(get_dispute_metrics)), + ), + ) + .service( + web::scope("/v2") + .service( + web::resource("/metrics/payments") + .route(web::post().to(get_payment_intents_metrics)), + ) + .service( + web::resource("/filters/payments") + .route(web::post().to(get_payment_intents_filters)), + ), + ) } } @@ -178,6 +198,42 @@ pub mod routes { .await } + /// # Panics + /// + /// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element. + pub async fn get_payment_intents_metrics( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>, + ) -> impl Responder { + // safety: This shouldn't panic owing to the data type + #[allow(clippy::expect_used)] + let payload = json_payload + .into_inner() + .to_vec() + .pop() + .expect("Couldn't get GetPaymentIntentMetricRequest"); + let flow = AnalyticsFlow::GetPaymentIntentMetrics; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + analytics::payment_intents::get_metrics( + &state.pool, + &auth.merchant_account.merchant_id, + req, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + /// # Panics /// /// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element. @@ -350,6 +406,32 @@ pub mod routes { .await } + pub async fn get_payment_intents_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetPaymentIntentFiltersRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetPaymentIntentFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req, _| async move { + analytics::payment_intents::get_filters( + &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_refund_filters( state: web::Data<AppState>, req: actix_web::HttpRequest,
2024-06-27T19:38:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added analytics based on `payment intent` Currently supporting 4 metrics - successful smart retries - total smart retries - smart retried amount - payment intent count filters - status - currency group by - status - currency ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Utilizing payment intents aligns closely with the data needs of merchants, enhancing their ability to manage and process transactions more effectively. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested using local data by sending cURL requests through Postman. Tested using Postgres data from `payment_intents` table and also using Clickhouse data from `payment_intent` table. <img width="959" alt="Screenshot 2024-06-28 at 12 33 21 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/be420744-297d-4263-aa8d-09653d097fc8"> ![Screenshot 2024-06-28 at 12 35 44 PM](https://github.com/juspay/hyperswitch/assets/83278309/878067a4-dd11-47ff-ab76-84196fff78a7) ![Screenshot 2024-06-28 at 12 36 05 PM](https://github.com/juspay/hyperswitch/assets/83278309/4fa8392f-aa18-4117-b88a-e96d9d312ec3) <img width="562" alt="Screenshot 2024-06-28 at 12 33 38 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/b2e9623c-a341-486c-b6ff-852ed308ecb0"> ![Screenshot 2024-06-28 at 12 37 02 PM](https://github.com/juspay/hyperswitch/assets/83278309/b996a927-fb93-45ce-ae44-4a2316368f5f) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2688d24d4963550ff3efee363194446a3c75cc59
juspay/hyperswitch
juspay__hyperswitch-5149
Bug: feat(events): add payment metadata to the payment intent events We generate payment intent events on db changes, for this we rely on the database payment intent struct for generating a corresponding struct (`KafkaPaymentIntent`). we need to add the metadata, hashed customer_email to the generated event as well.
diff --git a/config/development.toml b/config/development.toml index 556b2e24afe..31a507a69a2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -663,7 +663,7 @@ host = "https://localhost:9200" [opensearch.auth] auth = "basic" username = "admin" -password = "admin" +password = "0penS3arc#" region = "eu-central-1" [opensearch.indexes] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 28bf8fe8bb4..e2ac7b9ed9d 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -495,7 +495,7 @@ host = "https://opensearch:9200" [opensearch.auth] auth = "basic" username = "admin" -password = "admin" +password = "0penS3arc#" region = "eu-central-1" [opensearch.indexes] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index c0b9ce756f7..31f75c05c32 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -454,7 +454,7 @@ pub struct PaymentsRequest { /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, @@ -3557,7 +3557,7 @@ pub struct PaymentsResponse { /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index bc480c497ea..7f4aaeef29e 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -18,7 +18,7 @@ pub struct PaymentIntent { pub customer_id: Option<id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, @@ -77,7 +77,7 @@ pub struct PaymentIntentNew { pub customer_id: Option<id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, @@ -131,7 +131,7 @@ pub enum PaymentIntentUpdate { incremental_authorization_allowed: Option<bool>, }, MetadataUpdate { - metadata: pii::SecretSerdeValue, + metadata: serde_json::Value, updated_by: String, }, PaymentCreateUpdate { @@ -169,7 +169,7 @@ pub enum PaymentIntentUpdate { statement_descriptor_name: Option<String>, statement_descriptor_suffix: Option<String>, order_details: Option<Vec<pii::SecretSerdeValue>>, - metadata: Option<pii::SecretSerdeValue>, + metadata: Option<serde_json::Value>, payment_confirm_source: Option<storage_enums::PaymentSource>, updated_by: String, session_expiry: Option<PrimitiveDateTime>, @@ -230,7 +230,7 @@ pub struct PaymentIntentUpdateInternal { pub return_url: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: Option<PrimitiveDateTime>, diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 0c22c70bc36..fff5043ad95 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -21,7 +21,7 @@ pub struct PaymentIntent { pub customer_id: Option<id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index fb824a80798..48e0c63acfa 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -98,7 +98,7 @@ pub struct PaymentIntentNew { pub customer_id: Option<id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, @@ -147,7 +147,7 @@ pub enum PaymentIntentUpdate { incremental_authorization_allowed: Option<bool>, }, MetadataUpdate { - metadata: pii::SecretSerdeValue, + metadata: serde_json::Value, updated_by: String, }, PaymentCreateUpdate { @@ -185,7 +185,7 @@ pub enum PaymentIntentUpdate { statement_descriptor_name: Option<String>, statement_descriptor_suffix: Option<String>, order_details: Option<Vec<pii::SecretSerdeValue>>, - metadata: Option<pii::SecretSerdeValue>, + metadata: Option<serde_json::Value>, frm_metadata: Option<pii::SecretSerdeValue>, payment_confirm_source: Option<storage_enums::PaymentSource>, updated_by: String, @@ -245,7 +245,7 @@ pub struct PaymentIntentUpdateInternal { pub return_url: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: Option<PrimitiveDateTime>, diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index efd01397f69..7121ebefc6d 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -56,7 +56,7 @@ pub struct PaymentsAuthorizeData { pub surcharge_details: Option<SurchargeDetails>, pub customer_id: Option<String>, pub request_incremental_authorization: bool, - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub authentication_data: Option<AuthenticationData>, pub charges: Option<PaymentCharges>, @@ -102,7 +102,7 @@ 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>, + pub metadata: Option<serde_json::Value>, // This metadata is used to store the metadata shared during the payment intent request. // New amount for amount frame work @@ -346,7 +346,7 @@ pub struct CompleteAuthorizeData { pub connector_transaction_id: Option<String>, pub connector_meta: Option<serde_json::Value>, pub complete_authorize_url: Option<String>, - pub metadata: Option<pii::SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub customer_acceptance: Option<mandates::CustomerAcceptance>, // New amount for amount frame work pub minor_amount: MinorUnit, @@ -390,7 +390,7 @@ 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>, + pub metadata: Option<serde_json::Value>, // This metadata is used to store the metadata shared during the payment intent request. // minor amount data for amount framework diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 6b3054e7c38..81dbbb748e3 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -261,7 +261,7 @@ pub struct StripePaymentIntentRequest { pub shipping: Option<Shipping>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, - pub metadata: Option<SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub client_secret: Option<masking::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, @@ -478,7 +478,7 @@ pub struct StripePaymentIntentResponse { pub customer: Option<id_type::CustomerId>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, pub mandate: Option<String>, - pub metadata: Option<SecretSerdeValue>, + pub metadata: Option<serde_json::Value>, pub charges: Charges, pub connector: Option<String>, pub description: Option<String>, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 2f01da29832..db5ada51529 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -458,7 +458,7 @@ pub struct StripeSetupIntentResponse { pub object: String, pub status: StripeSetupStatus, pub client_secret: Option<masking::Secret<String>>, - pub metadata: Option<secret::SecretSerdeValue>, + pub metadata: Option<Value>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, pub customer: Option<id_type::CustomerId>, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 9a85522396d..63c7bed5d0d 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2610,7 +2610,7 @@ impl<'a> channel: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } @@ -2673,7 +2673,7 @@ impl<'a> channel: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } @@ -2727,7 +2727,7 @@ impl<'a> channel: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }; Ok(request) @@ -2782,7 +2782,7 @@ impl<'a> channel: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }; Ok(request) @@ -2833,7 +2833,7 @@ impl<'a> channel: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }; Ok(request) @@ -2884,7 +2884,7 @@ impl<'a> social_security_number: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }; Ok(request) @@ -2945,7 +2945,7 @@ impl<'a> channel: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } @@ -3041,7 +3041,7 @@ impl<'a> channel, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } @@ -3117,7 +3117,7 @@ impl<'a> channel: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } @@ -3176,7 +3176,7 @@ impl<'a> social_security_number: None, shopper_statement: item.router_data.request.statement_descriptor.clone(), shopper_ip: item.router_data.request.get_ip_address_as_optional(), - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(), }) } diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 1230843afa9..d26c01e9a84 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -941,10 +941,12 @@ impl 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()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { processing_information, @@ -976,10 +978,12 @@ impl let payment_information = PaymentInformation::try_from(&ccard)?; let processing_information = ProcessingInformation::try_from((item, None, None))?; 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()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { processing_information, @@ -1017,10 +1021,12 @@ impl ))?; let client_reference_information = ClientReferenceInformation::from(item); let payment_information = PaymentInformation::try_from(&apple_pay_data)?; - let merchant_defined_information = - item.router_data.request.metadata.clone().map(|metadata| { - Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); let ucaf_collection_indicator = match apple_pay_wallet_data .payment_method .network @@ -1068,10 +1074,12 @@ impl let processing_information = ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?; 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()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { processing_information, @@ -1132,7 +1140,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { Vec::<MerchantDefinedInformation>::foreign_from( - metadata.peek().to_owned(), + metadata, ) }); let ucaf_collection_indicator = match apple_pay_data @@ -1307,10 +1315,12 @@ impl 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()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { processing_information, payment_information, @@ -2610,10 +2620,12 @@ 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()) - }); + let merchant_defined_information = value + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { order_information: OrderInformation { amount_details: Amount { @@ -2653,10 +2665,12 @@ 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()) - }); + let merchant_defined_information = value + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs index ddaa58cfd04..c00303fc5e9 100644 --- a/crates/router/src/connector/billwerk/transformers.rs +++ b/crates/router/src/connector/billwerk/transformers.rs @@ -202,7 +202,7 @@ impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for Billw first_name: item.router_data.get_optional_billing_first_name(), last_name: item.router_data.get_optional_billing_last_name(), }, - metadata: item.router_data.request.metadata.clone(), + metadata: item.router_data.request.metadata.clone().map(Into::into), settle: item.router_data.request.is_auto_capture()?, }) } diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index fbc7c661e4c..d1d5f1d8c9e 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -258,7 +258,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues .metadata .as_ref() .map(|metadata| BluesnapMetadata { - meta_data: Vec::<RequestMetadata>::foreign_from(metadata.peek().to_owned()), + meta_data: Vec::<RequestMetadata>::foreign_from(metadata.to_owned()), }); let (payment_method, card_holder_info) = match item @@ -609,7 +609,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>> .metadata .as_ref() .map(|metadata| BluesnapMetadata { - meta_data: Vec::<RequestMetadata>::foreign_from(metadata.peek().to_owned()), + meta_data: Vec::<RequestMetadata>::foreign_from(metadata.to_owned()), }); let token = item diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 0a73d135f43..e035c102d20 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -418,7 +418,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme let connector_auth = &item.router_data.connector_auth_type; let auth_type: CheckoutAuthType = connector_auth.try_into()?; let processing_channel_id = auth_type.processing_channel_id; - let metadata = item.router_data.request.metadata.clone(); + let metadata = item.router_data.request.metadata.clone().map(Into::into); Ok(Self { source: source_var, amount: item.amount.to_owned(), diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index dcaa2ffb2f1..38514fc45f9 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -991,10 +991,12 @@ impl let processing_information = ProcessingInformation::try_from((item, None, card_type))?; 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()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); let consumer_authentication_information = item .router_data @@ -1097,10 +1099,12 @@ impl veres_enrolled: None, }); - let merchant_defined_information = - item.router_data.request.metadata.clone().map(|metadata| { - Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { processing_information, @@ -1149,10 +1153,12 @@ impl expiration_month, }, })); - let merchant_defined_information = - item.router_data.request.metadata.clone().map(|metadata| { - Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); let ucaf_collection_indicator = match apple_pay_wallet_data .payment_method .network @@ -1211,10 +1217,12 @@ impl let processing_information = ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?; 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()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { processing_information, @@ -1284,7 +1292,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { Vec::<MerchantDefinedInformation>::foreign_from( - metadata.peek().to_owned(), + metadata, ) }); let ucaf_collection_indicator = match apple_pay_data @@ -1411,10 +1419,12 @@ impl 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()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { processing_information, payment_information, @@ -1510,10 +1520,12 @@ 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()) - }); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { processing_information: ProcessingInformation { capture_options: Some(CaptureOptions { @@ -1602,10 +1614,12 @@ 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()) - }); + let merchant_defined_information = value + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.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 c9d86b17ba8..a87b8e6176d 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -1,12 +1,7 @@ use api_models::webhooks; use cards::CardNumber; use common_enums::CountryAlpha2; -use common_utils::{ - errors::CustomResult, - ext_traits::XmlExt, - pii::{self, Email}, - types::FloatMajorUnit, -}; +use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit}; use error_stack::{report, Report, ResultExt}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -431,8 +426,8 @@ pub struct NmiMerchantDefinedField { } impl NmiMerchantDefinedField { - pub fn new(metadata: &pii::SecretSerdeValue) -> Self { - let metadata_as_string = metadata.peek().to_string(); + pub fn new(metadata: &serde_json::Value) -> Self { + let metadata_as_string = metadata.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 diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index d79774b2e87..6de5ba5e6d1 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -1,6 +1,6 @@ use common_utils::{ext_traits::Encode, pii, types::StringMajorUnit}; use error_stack::ResultExt; -use masking::{ExposeInterface, PeekInterface, Secret}; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -107,8 +107,8 @@ fn get_value_as_string(value: &serde_json::Value) -> String { } impl NoonOrderNvp { - pub fn new(metadata: &pii::SecretSerdeValue) -> Self { - let metadata_as_string = metadata.peek().to_string(); + pub fn new(metadata: &serde_json::Value) -> Self { + let metadata_as_string = metadata.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 diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 53850e97afc..ddd56846741 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1840,7 +1840,8 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent } }); - let meta_data = get_transaction_metadata(item.request.metadata.clone(), order_id); + let meta_data = + get_transaction_metadata(item.request.metadata.clone().map(Into::into), order_id); // We pass browser_info only when payment_data exists. // Hence, we're pass Null during recurring payments as payment_method_data[type] is not passed @@ -3334,7 +3335,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for ChargesReques let amount = data.1; let order_id = value.connector_request_reference_id.clone(); let meta_data = Some(get_transaction_metadata( - value.request.metadata.clone(), + value.request.metadata.clone().map(Into::into), order_id, )); Ok(Self { diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 67ba0219642..e9657c6cfc5 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -922,16 +922,14 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { } fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> { - self.metadata - .clone() - .and_then(|meta_data| match meta_data.peek() { - serde_json::Value::Null - | serde_json::Value::Bool(_) - | serde_json::Value::Number(_) - | serde_json::Value::String(_) - | serde_json::Value::Array(_) => None, - serde_json::Value::Object(_) => Some(meta_data), - }) + self.metadata.clone().and_then(|meta_data| match meta_data { + serde_json::Value::Null + | serde_json::Value::Bool(_) + | serde_json::Value::Number(_) + | serde_json::Value::String(_) + | serde_json::Value::Array(_) => None, + serde_json::Value::Object(_) => Some(meta_data.into()), + }) } fn get_authentication_data(&self) -> Result<AuthenticationData, Error> { diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 69c82d4f2d7..0d0eace13e3 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -320,7 +320,7 @@ where .or_else(|| // when the order_details are present within the meta_data, we need to take those to support backward compatibility payment_data.payment_intent.metadata.clone().and_then(|meta| { - let order_details = meta.peek().get("order_details").to_owned(); + let order_details = meta.get("order_details").to_owned(); order_details.map(|order| vec![masking::Secret::new(order.to_owned())]) })) .map(|order_details_value| { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 62167d592e9..b9b3aa134dd 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1690,7 +1690,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ Some(RequestIncrementalAuthorization::True) | Some(RequestIncrementalAuthorization::Default) ), - metadata: payment_data.payment_intent.metadata.clone(), + metadata: payment_data.payment_intent.metadata.clone().map(Into::into), }) } } diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index 7a74f07e3b2..8491ddbb91e 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -14,6 +14,7 @@ pub struct KafkaPaymentIntent<'a> { pub customer_id: Option<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, + pub metadata: Option<String>, pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, @@ -45,6 +46,7 @@ impl<'a> KafkaPaymentIntent<'a> { customer_id: intent.customer_id.as_ref(), description: intent.description.as_ref(), return_url: intent.return_url.as_ref(), + metadata: intent.metadata.as_ref().map(|x| x.to_string()), connector_id: intent.connector_id.as_ref(), statement_descriptor_name: intent.statement_descriptor_name.as_ref(), statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index a3fbd9ddc45..dccd301151a 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -15,6 +15,7 @@ pub struct KafkaPaymentIntentEvent<'a> { pub customer_id: Option<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, + pub metadata: Option<String>, pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, @@ -46,6 +47,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> { customer_id: intent.customer_id.as_ref(), description: intent.description.as_ref(), return_url: intent.return_url.as_ref(), + metadata: intent.metadata.as_ref().map(|x| x.to_string()), connector_id: intent.connector_id.as_ref(), statement_descriptor_name: intent.statement_descriptor_name.as_ref(), statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), diff --git a/docker-compose.yml b/docker-compose.yml index 3a6ff1e4047..9c8aa61dc90 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -379,6 +379,7 @@ services: environment: - "discovery.type=single-node" - OPENSEARCH_INITIAL_ADMIN_PASSWORD=0penS3arc# + - LOG_LEVEL=DEBUG profiles: - olap ports: diff --git a/docker/fluentd/conf/fluent.conf b/docker/fluentd/conf/fluent.conf index 7aec9dd7cd8..785254a3b25 100644 --- a/docker/fluentd/conf/fluent.conf +++ b/docker/fluentd/conf/fluent.conf @@ -125,7 +125,7 @@ index_name hyperswitch-dispute-events id_key dispute_id user admin - password admin + password '0penS3arc#' ssl_verify false prefer_oj_serializer true reload_on_failure true
2024-07-01T13:39:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - `metadata` is marked as `pii::SecretSerdeValue`, now changed it to `serde_json::Value` to remove the masking. - Added the `metadata` field for `hyperswitch-payment-intent-events` (type - String). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 the metadata to the payment-intent-event helps in providing better information about the event. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Make a normal payment through Postman by following the steps: - Merchant Account - Create - API Key - Create - Payment Connector - Create - Payments - Create You should now be able to see the `metadata` field in hyperswitch-payment-intent-events when viewed in kafka-ui. <img width="1495" alt="Screenshot 2024-07-01 at 6 57 29 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/f678591d-1d83-4b18-856e-f650cb2eeb6f"> And can also be searched using global search in the dashboard. <img width="805" alt="Screenshot 2024-07-02 at 1 06 11 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/b2c0d10f-d55d-487c-8950-4aa22ca21559"> <img width="418" alt="Screenshot 2024-07-02 at 1 06 54 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/e467ed28-b95c-4301-b90d-47b672f142f2"> Metadata is of type - String <img width="1327" alt="Screenshot 2024-07-02 at 3 55 37 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/ebc47d7b-6427-43d3-84c4-4302ccf62746"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c642d9dcf5e2bb9a91d543731e33ce5fe3e81b95
juspay/hyperswitch
juspay__hyperswitch-5131
Bug: feat: add connector zsl and local bank transfer payment method to dashboard ### Feature Description Add ZSL to dashboard connectors and add local bank transfer payment method type to dashboard ### 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/config/config.example.toml b/config/config.example.toml index 56d4500cba2..6f880acbba4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -79,6 +79,7 @@ sampling_rate = 0.1 # decimal rate between 0.0 - 1.0 [secrets] admin_api_key = "test_admin" # admin API key for admin authentication jwt_secret = "secret" # JWT secret used for user authentication +master_enc_key = "sample_key" # Master Encryption key used to encrypt merchant wise encryption key. Should be 32-byte long. # Locker settings contain details for accessing a card locker, a # PCI Compliant storage entity which stores payment method information diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 4b48d4292e0..50034a87604 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -33,6 +33,8 @@ impl Default for super::settings::Secrets { Self { jwt_secret: "secret".into(), admin_api_key: "test_admin".into(), + master_enc_key: "73ad7bbbbc640c845a150f67d058b279849370cd2c1f3c67c4dd6c869213e13a" + .into(), } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a8719e221a3..2a3bcc7355e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -158,6 +158,7 @@ where pub struct Secrets { pub jwt_secret: String, pub admin_api_key: String, + pub master_enc_key: String, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 0d6e4273e83..fa42f9dee28 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1,5 +1,6 @@ use common_utils::{ - crypto::{self, GcmAes256, OptionalSecretValue}, + crypto::OptionalSecretValue, + date_time, ext_traits::{AsyncExt, ValueExt}, }; use error_stack::{report, FutureExt, IntoReport, ResultExt}; @@ -15,12 +16,12 @@ use crate::{ }, db::StorageInterface, routes::AppState, - services::api as service_api, + services::{self, api as service_api}, types::{ self, api, domain::{ - self, merchant_account as merchant_domain, - types::{get_key_and_algo, AsyncLift, TypeEncryption}, + self, merchant_account as merchant_domain, merchant_key_store, + types::{self as domain_types, AsyncLift}, }, storage, transformers::ForeignInto, @@ -42,6 +43,12 @@ pub async fn create_merchant_account( req: api::MerchantAccountCreate, ) -> RouterResponse<api::MerchantAccountResponse> { let db = &*state.store; + let master_key = db.get_master_key(); + + let key = services::generate_aes256_key() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to generate aes 256 key")?; + let publishable_key = Some(create_merchant_publishable_key()); let api_key_request = api::CreateApiKeyRequest { @@ -53,10 +60,6 @@ pub async fn create_merchant_account( expiration: api::ApiKeyExpiration::Never, }; - let key = get_key_and_algo(db, req.merchant_id.clone()) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - let api_key = match api_keys::create_api_key( db, &state.conf.api_keys, @@ -100,16 +103,31 @@ pub async fn create_merchant_account( .attach_printable("Invalid routing algorithm given")?; } + let key_store = merchant_key_store::MerchantKeyStore { + merchant_id: req.merchant_id.clone(), + key: domain_types::encrypt(key.to_vec().into(), master_key) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to decrypt data from key store")?, + created_at: date_time::now(), + }; + + db.insert_merchant_key_store(key_store) + .await + .map_err(|error| { + error.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount) + })?; + let encrypt_string = |inner: Option<masking::Secret<String>>| async { inner - .async_map(|value| crypto::Encryptable::encrypt(value, &key, GcmAes256 {})) + .async_map(|value| domain_types::encrypt(value, &key)) .await .transpose() }; let encrypt_value = |inner: OptionalSecretValue| async { inner - .async_map(|value| crypto::Encryptable::encrypt(value, &key, GcmAes256 {})) + .async_map(|value| domain_types::encrypt(value, &key)) .await .transpose() }; @@ -121,10 +139,7 @@ pub async fn create_merchant_account( Ok(merchant_domain::MerchantAccount { merchant_id: req.merchant_id, merchant_name: req.merchant_name.async_lift(encrypt_string).await?, - api_key: Some( - crypto::Encryptable::encrypt(api_key.peek().clone().into(), &key, GcmAes256 {}) - .await?, - ), + api_key: Some(domain_types::encrypt(api_key.peek().clone().into(), &key).await?), merchant_details: merchant_details.async_lift(encrypt_value).await?, return_url: req.return_url.map(|a| a.to_string()), webhook_details, @@ -152,7 +167,6 @@ pub async fn create_merchant_account( .map_err(|error| { error.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount) })?; - Ok(service_api::ApplicationResponse::Json( merchant_account.into(), )) @@ -179,9 +193,10 @@ pub async fn merchant_account_update( merchant_id: &String, req: api::MerchantAccountUpdate, ) -> RouterResponse<api::MerchantAccountResponse> { - let key = get_key_and_algo(db, merchant_id.clone()) + let key = domain_types::get_merchant_enc_key(db, merchant_id.clone()) .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to get data from merchant key store")?; if &req.merchant_id != merchant_id { Err(report!(errors::ValidationError::IncorrectValueProvided { @@ -205,24 +220,41 @@ pub async fn merchant_account_update( .attach_printable("Invalid routing algorithm given")?; } + let encrypt_string = |inner: Option<masking::Secret<String>>| async { + inner + .async_map(|value| domain_types::encrypt(value, &key)) + .await + .transpose() + }; + + let encrypt_value = |inner: OptionalSecretValue| async { + inner + .async_map(|value| domain_types::encrypt(value, &key)) + .await + .transpose() + }; + let updated_merchant_account = storage::MerchantAccountUpdate::Update { merchant_name: req .merchant_name - .async_map(|inner| crypto::Encryptable::encrypt(inner.into(), &key, GcmAes256 {})) + .map(masking::Secret::new) + .async_lift(encrypt_string) .await - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError)?, + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt merchant name")?, merchant_details: req .merchant_details .as_ref() .map(utils::Encode::<api::MerchantDetails>::encode_to_value) .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError)? - .async_map(|inner| crypto::Encryptable::encrypt(inner.into(), &key, GcmAes256 {})) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to convert merchant_details to a value")? + .map(masking::Secret::new) + .async_lift(encrypt_value) .await - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError)?, + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt merchant details")?, return_url: req.return_url.map(|a| a.to_string()), @@ -323,6 +355,11 @@ pub async fn create_payment_connector( req: api::MerchantConnector, merchant_id: &String, ) -> RouterResponse<api::MerchantConnector> { + let key = domain_types::get_merchant_enc_key(store, merchant_id.clone()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to get key from merchant key store")?; + let _merchant_account = store .find_merchant_account_by_merchant_id(merchant_id) .await @@ -362,11 +399,17 @@ pub async fn create_payment_connector( connector_type: req.connector_type.foreign_into(), connector_name: req.connector_name, merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"), - connector_account_details: req.connector_account_details.ok_or( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "connector_account_details", - }, - )?, + connector_account_details: domain_types::encrypt( + req.connector_account_details.ok_or( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "connector_account_details", + }, + )?, + &key, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt connector account details")?, payment_methods_enabled, test_mode: req.test_mode, disabled: req.disabled, @@ -444,6 +487,11 @@ pub async fn update_payment_connector( merchant_connector_id: &str, req: api::MerchantConnector, ) -> RouterResponse<api::MerchantConnector> { + let key = domain_types::get_merchant_enc_key(db, merchant_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to get key from merchant key store")?; + let _merchant_account = db .find_merchant_account_by_merchant_id(merchant_id) .await @@ -470,12 +518,24 @@ pub async fn update_payment_connector( .collect::<Vec<serde_json::Value>>() }); + let encrypt = |inner: Option<masking::Secret<serde_json::Value>>| async { + inner + .async_map(|inner| domain_types::encrypt(inner, &key)) + .await + .transpose() + }; + let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: Some(merchant_id.to_string()), connector_type: Some(req.connector_type.foreign_into()), connector_name: Some(req.connector_name), merchant_connector_id: Some(merchant_connector_id.to_string()), - connector_account_details: req.connector_account_details, + connector_account_details: req + .connector_account_details + .async_lift(encrypt) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt connector_account_details")?, payment_methods_enabled, test_mode: req.test_mode, disabled: req.disabled, @@ -483,7 +543,7 @@ pub async fn update_payment_connector( }; let updated_mca = db - .update_merchant_connector_account(mca, payment_connector) + .update_merchant_connector_account(mca, payment_connector.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { @@ -505,7 +565,7 @@ pub async fn update_payment_connector( connector_type: updated_mca.connector_type.foreign_into(), connector_name: updated_mca.connector_name, merchant_connector_id: Some(updated_mca.merchant_connector_id), - connector_account_details: Some(updated_mca.connector_account_details), + connector_account_details: Some(updated_mca.connector_account_details.into_inner()), test_mode: updated_mca.test_mode, disabled: updated_mca.disabled, payment_methods_enabled: updated_pm_enabled, diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 3ae20a34cf3..6be36d971dd 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -1,5 +1,5 @@ use common_utils::{ - crypto::{self, Encryptable, GcmAes256}, + crypto::{Encryptable, GcmAes256}, ext_traits::{AsyncExt, ValueExt}, }; use error_stack::ResultExt; @@ -20,7 +20,7 @@ use crate::{ api::customers::{self, CustomerRequestExt}, domain::{ self, customer, merchant_account, - types::{get_key_and_algo, AsyncLift, TypeEncryption}, + types::{self, AsyncLift, TypeEncryption}, }, storage::{self, enums}, }, @@ -40,21 +40,21 @@ pub async fn create_customer( let merchant_id = &merchant_account.merchant_id; customer_data.merchant_id = merchant_id.to_owned(); - let key = get_key_and_algo(db, merchant_id.clone()) + let key = types::get_merchant_enc_key(db, merchant_id.clone()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting encryption key")?; let encrypt = |inner: Option<masking::Secret<String>>| async { inner - .async_map(|value| crypto::Encryptable::encrypt(value, &key, GcmAes256 {})) + .async_map(|value| types::encrypt(value, &key)) .await .transpose() }; let encrypt_email = |inner: Option<masking::Secret<String, pii::Email>>| async { inner - .async_map(|value| crypto::Encryptable::encrypt(value, &key, GcmAes256 {})) + .async_map(|value| types::encrypt(value, &key)) .await .transpose() }; @@ -214,7 +214,7 @@ pub async fn delete_customer( }?, }; - let key = get_key_and_algo(&**db, merchant_account.merchant_id.clone()) + let key = types::get_merchant_enc_key(&**db, merchant_account.merchant_id.clone()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting key for encryption")?; @@ -300,21 +300,21 @@ pub async fn update_customer( .await .map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound))?; - let key = get_key_and_algo(db, merchant_account.merchant_id.clone()) + let key = types::get_merchant_enc_key(db, merchant_account.merchant_id.clone()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting key for encryption")?; let encrypt = |inner: Option<masking::Secret<String>>| async { inner - .async_map(|value| crypto::Encryptable::encrypt(value, &key, GcmAes256 {})) + .async_map(|value| types::encrypt(value, &key)) .await .transpose() }; let encrypt_email = |inner: Option<masking::Secret<String, pii::Email>>| async { inner - .async_map(|value| crypto::Encryptable::encrypt(value, &key, GcmAes256 {})) + .async_map(|value| types::encrypt(value, &key)) .await .transpose() }; diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index bd918b899a8..585afd21486 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -71,6 +71,10 @@ pub enum StorageError { CustomerRedacted, #[error("Deserialization failure")] DeserializationFailed, + #[error("Error while encrypting data")] + EncryptionError, + #[error("Error while decrypting data from database")] + DecryptionError, #[error("RedisError: {0:?}")] RedisError(error_stack::Report<RedisError>), } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 79f4dd46ab0..9bc55fd7bc1 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -29,7 +29,10 @@ use crate::{ }, db, logger, pii::prelude::*, - routes::{self, metrics}, + routes::{ + self, + metrics::{self, request}, + }, services, types::{ api::{self, PaymentMethodCreateExt}, @@ -162,7 +165,7 @@ pub async fn add_card_to_locker( merchant_account: &merchant_account::MerchantAccount, ) -> errors::CustomResult<api::PaymentMethodResponse, errors::VaultError> { metrics::STORED_TO_LOCKER.add(&metrics::CONTEXT, 1, &[]); - metrics::request::record_card_operation_time( + request::record_operation_time( async { match state.conf.locker.locker_setup { settings::LockerSetup::BasiliskLocker => { @@ -191,7 +194,7 @@ pub async fn get_card_from_locker( ) -> errors::RouterResult<payment_methods::Card> { metrics::GET_FROM_LOCKER.add(&metrics::CONTEXT, 1, &[]); - metrics::request::record_card_operation_time( + request::record_operation_time( async { match state.conf.locker.locker_setup { settings::LockerSetup::LegacyLocker => { @@ -227,7 +230,7 @@ pub async fn delete_card_from_locker( ) -> errors::RouterResult<payment_methods::DeleteCardResp> { metrics::DELETE_FROM_LOCKER.add(&metrics::CONTEXT, 1, &[]); - metrics::request::record_card_operation_time( + request::record_operation_time( async { match state.conf.locker.locker_setup { settings::LockerSetup::LegacyLocker => { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 658dcb182b2..29ae6330a83 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -32,7 +32,7 @@ use crate::{ api::{self, admin, enums as api_enums, CustomerAcceptanceExt, MandateValidationFieldsExt}, domain::{ self, customer, merchant_account, - types::{get_key_and_algo, AsyncLift, TypeEncryption}, + types::{self, AsyncLift}, }, storage::{self, enums as storage_enums, ephemeral_key}, transformers::ForeignInto, @@ -51,14 +51,14 @@ pub async fn get_address_for_payment_request( merchant_id: &str, customer_id: &Option<String>, ) -> CustomResult<Option<domain::address::Address>, errors::ApiErrorResponse> { - let key = get_key_and_algo(db, merchant_id.to_string()) + let key = types::get_merchant_enc_key(db, merchant_id.to_string()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting key for encryption")?; let encrypt = |inner: Option<masking::Secret<String>>| async { inner - .async_map(|value| crypto::Encryptable::encrypt(value, &key, crypto::GcmAes256 {})) + .async_map(|value| types::encrypt(value, &key)) .await .transpose() }; @@ -783,22 +783,18 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( Some(match customer_data { Some(c) => Ok(c), None => { - let key = get_key_and_algo(db, merchant_id.to_string()).await?; + let key = types::get_merchant_enc_key(db, merchant_id.to_string()).await?; let encrypt = |inner: Option<masking::Secret<String>>| async { inner - .async_map(|value| { - crypto::Encryptable::encrypt(value, &key, crypto::GcmAes256 {}) - }) + .async_map(|value| types::encrypt(value, &key)) .await .transpose() }; let encrypt_email = |inner: Option<masking::Secret<String, pii::Email>>| async { inner - .async_map(|value| { - crypto::Encryptable::encrypt(value, &key, crypto::GcmAes256 {}) - }) + .async_map(|value| types::encrypt(value, &key)) .await .transpose() }; diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 9e8c08f1d2e..262b9b31f04 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -12,6 +12,7 @@ pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; +pub mod merchant_key_store; pub mod payment_attempt; pub mod payment_intent; pub mod payment_method; @@ -59,11 +60,33 @@ pub trait StorageInterface: + refund::RefundInterface + reverse_lookup::ReverseLookupInterface + cards_info::CardsInfoInterface + + merchant_key_store::MerchantKeyStoreInterface + + MasterKeyInterface + 'static { async fn close(&mut self) {} } +pub trait MasterKeyInterface { + fn get_master_key(&self) -> &[u8]; +} + +impl MasterKeyInterface for Store { + fn get_master_key(&self) -> &[u8] { + &self.master_key + } +} + +/// Default dummy key for MockDb +impl MasterKeyInterface for MockDb { + fn get_master_key(&self) -> &[u8] { + &[ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, + ] + } +} + #[async_trait::async_trait] impl StorageInterface for Store { #[allow(clippy::expect_used)] diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 29da891d052..eb6ee3d77c9 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -56,10 +56,11 @@ impl AddressInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|address| async { + let merchant_id = address.merchant_id.clone(); address - .convert() + .convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -75,10 +76,11 @@ impl AddressInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|address| async { + let merchant_id = address.merchant_id.clone(); address - .convert() + .convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -91,16 +93,17 @@ impl AddressInterface for Store { address .construct_new() .await - .change_context(errors::StorageError::DeserializationFailed)? + .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(Into::into) .into_report() .async_and_then(|address| async { + let merchant_id = address.merchant_id.clone(); address - .convert() + .convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -124,11 +127,12 @@ impl AddressInterface for Store { .async_and_then(|addresses| async { let mut output = Vec::with_capacity(addresses.len()); for address in addresses.into_iter() { + let merchant_id = address.merchant_id.clone(); output.push( address - .convert() + .convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed)?, + .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs index 9c54e34ba35..77e7f8fb099 100644 --- a/crates/router/src/db/customers.rs +++ b/crates/router/src/db/customers.rs @@ -72,9 +72,9 @@ impl CustomerInterface for Store { .map_err(Into::into) .into_report()? .async_map(|c| async { - c.convert() + c.convert(self, merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; @@ -107,9 +107,10 @@ impl CustomerInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|c| async { - c.convert() + let merchant_id = c.merchant_id.clone(); + c.convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -126,9 +127,10 @@ impl CustomerInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|c| async { - c.convert() + let merchant_id = c.merchant_id.clone(); + c.convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await?; match customer.name { @@ -147,15 +149,16 @@ impl CustomerInterface for Store { customer_data .construct_new() .await - .change_context(errors::StorageError::DeserializationFailed)? + .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(Into::into) .into_report() .async_and_then(|c| async { - c.convert() + let merchant_id = c.merchant_id.clone(); + c.convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -190,9 +193,10 @@ impl CustomerInterface for MockDb { .cloned(); customer .async_map(|c| async { - c.convert() + let merchant_id = c.merchant_id.clone(); + c.convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await .transpose() @@ -226,13 +230,15 @@ impl CustomerInterface for MockDb { let customer = Conversion::convert(customer_data) .await - .change_context(errors::StorageError::SerializationFailed)?; + .change_context(errors::StorageError::EncryptionError)?; + + let merchant_id = customer.merchant_id.clone(); customers.push(customer.clone()); customer - .convert() + .convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) } async fn delete_customer_by_customer_id_merchant_id( diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index bb79863a811..b88db0d1947 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -1,6 +1,8 @@ use common_utils::ext_traits::AsyncExt; use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "accounts_cache")] +use super::cache; use super::{MockDb, Store}; use crate::{ connection, @@ -10,7 +12,7 @@ use crate::{ behaviour::{Conversion, ReverseConversion}, merchant_account, }, - storage::{self}, + storage, }, }; @@ -60,17 +62,18 @@ impl MerchantAccountInterface for Store { merchant_account: merchant_account::MerchantAccount, ) -> CustomResult<merchant_account::MerchantAccount, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; + let merchant_id = merchant_account.merchant_id.clone(); merchant_account .construct_new() .await - .change_context(errors::StorageError::DeserializationFailed)? + .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(Into::into) .into_report()? - .convert() + .convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) } async fn find_merchant_account_by_merchant_id( @@ -89,18 +92,18 @@ impl MerchantAccountInterface for Store { { fetch_func() .await? - .convert() + .convert(self, merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { - super::cache::get_or_populate_redis(self, merchant_id, fetch_func) + cache::get_or_populate_redis(self, merchant_id, fetch_func) .await? - .convert() + .convert(self, merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) } } @@ -114,15 +117,15 @@ impl MerchantAccountInterface for Store { let conn = connection::pg_connection_write(self).await?; Conversion::convert(this) .await - .change_context(errors::StorageError::DeserializationFailed)? + .change_context(errors::StorageError::EncryptionError)? .update(&conn, merchant_account.into()) .await .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert() + item.convert(self, &_merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await }; @@ -134,7 +137,7 @@ impl MerchantAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - super::cache::redact_cache(self, &_merchant_id, update_func, None).await + cache::redact_cache(self, &_merchant_id, update_func, None).await } } @@ -154,9 +157,9 @@ impl MerchantAccountInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert() + item.convert(self, merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await }; @@ -168,7 +171,7 @@ impl MerchantAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - super::cache::redact_cache(self, merchant_id, update_func, None).await + cache::redact_cache(self, merchant_id, update_func, None).await } } @@ -182,9 +185,10 @@ impl MerchantAccountInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert() + let merchant_id = item.merchant_id.clone(); + item.convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -208,7 +212,7 @@ impl MerchantAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - super::cache::redact_cache(self, merchant_id, delete_func, None).await + cache::redact_cache(self, merchant_id, delete_func, None).await } } } @@ -223,13 +227,14 @@ impl MerchantAccountInterface for MockDb { let mut accounts = self.merchant_accounts.lock().await; let account = Conversion::convert(merchant_account) .await - .change_context(errors::StorageError::SerializationFailed)?; + .change_context(errors::StorageError::EncryptionError)?; + let merchant_id = account.merchant_id.clone(); accounts.push(account.clone()); account - .convert() + .convert(self, &merchant_id) .await - .change_context(errors::StorageError::SerializationFailed) + .change_context(errors::StorageError::DecryptionError) } #[allow(clippy::panic)] @@ -243,9 +248,9 @@ impl MerchantAccountInterface for MockDb { .find(|account| account.merchant_id == merchant_id) .cloned() .async_map(|a| async { - a.convert() + a.convert(self, merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index d84908193a7..33e5592350d 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,7 +1,8 @@ use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode}; use error_stack::{IntoReport, ResultExt}; -use masking::ExposeInterface; +#[cfg(feature = "accounts_cache")] +use super::cache; use super::{MockDb, Store}; use crate::{ connection, @@ -149,7 +150,7 @@ where async fn update_merchant_connector_account( &self, this: domain::merchant_connector_account::MerchantConnectorAccount, - merchant_connector_account: storage::MerchantConnectorAccountUpdate, + merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, ) -> CustomResult< domain::merchant_connector_account::MerchantConnectorAccount, errors::StorageError, @@ -182,9 +183,9 @@ impl MerchantConnectorAccountInterface for Store { .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert() + item.convert(self, merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -207,21 +208,24 @@ impl MerchantConnectorAccountInterface for Store { .await .map_err(Into::into) .into_report() - .async_and_then(|item| async { - item.convert() - .await - .change_context(errors::StorageError::DeserializationFailed) - }) - .await }; + #[cfg(not(feature = "accounts_cache"))] { - find_call().await + find_call() + .await? + .convert(self, merchant_id) + .await + .change_context(errors::StorageError::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { - super::cache::get_or_populate_redis(self, merchant_connector_id, find_call).await + cache::get_or_populate_redis(self, merchant_connector_id, find_call) + .await? + .convert(self, merchant_id) + .await + .change_context(errors::StorageError::DeserializationFailed) } } @@ -235,15 +239,16 @@ impl MerchantConnectorAccountInterface for Store { let conn = connection::pg_connection_write(self).await?; t.construct_new() .await - .change_context(errors::StorageError::DeserializationFailed)? + .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert() + let merchant_id = item.merchant_id.clone(); + item.convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -265,9 +270,9 @@ impl MerchantConnectorAccountInterface for Store { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( - item.convert() + item.convert(self, merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed)?, + .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) @@ -278,7 +283,7 @@ impl MerchantConnectorAccountInterface for Store { async fn update_merchant_connector_account( &self, this: domain::merchant_connector_account::MerchantConnectorAccount, - merchant_connector_account: storage::MerchantConnectorAccountUpdate, + merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, ) -> CustomResult< domain::merchant_connector_account::MerchantConnectorAccount, errors::StorageError, @@ -288,22 +293,23 @@ impl MerchantConnectorAccountInterface for Store { let conn = connection::pg_connection_write(self).await?; Conversion::convert(this) .await - .change_context(errors::StorageError::DeserializationFailed)? + .change_context(errors::StorageError::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(Into::into) .into_report() .async_and_then(|item| async { - item.convert() + let merchant_id = item.merchant_id.clone(); + item.convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { - super::cache::redact_cache(self, &_merchant_connector_id, update_call, None).await + cache::redact_cache(self, &_merchant_connector_id, update_call, None).await } #[cfg(not(feature = "accounts_cache"))] @@ -350,9 +356,9 @@ impl MerchantConnectorAccountInterface for MockDb { .cloned() .unwrap(); account - .convert() + .convert(self, merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) } async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( @@ -376,12 +382,13 @@ impl MerchantConnectorAccountInterface for MockDb { errors::StorageError, > { let mut accounts = self.merchant_connector_accounts.lock().await; + let merchant_id = t.merchant_id.clone(); let account = storage::MerchantConnectorAccount { #[allow(clippy::as_conversions)] id: accounts.len() as i32, merchant_id: t.merchant_id, connector_name: t.connector_name, - connector_account_details: t.connector_account_details.expose(), + connector_account_details: t.connector_account_details.into(), test_mode: t.test_mode, disabled: t.disabled, merchant_connector_id: t.merchant_connector_id, @@ -391,9 +398,9 @@ impl MerchantConnectorAccountInterface for MockDb { }; accounts.push(account.clone()); account - .convert() + .convert(self, &merchant_id) .await - .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::StorageError::DecryptionError) } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( @@ -411,7 +418,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn update_merchant_connector_account( &self, _this: domain::merchant_connector_account::MerchantConnectorAccount, - _merchant_connector_account: storage::MerchantConnectorAccountUpdate, + _merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, ) -> CustomResult< domain::merchant_connector_account::MerchantConnectorAccount, errors::StorageError, diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs new file mode 100644 index 00000000000..b4637af8c0c --- /dev/null +++ b/crates/router/src/db/merchant_key_store.rs @@ -0,0 +1,81 @@ +use error_stack::{IntoReport, ResultExt}; + +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::MockDb, + services::Store, + types::domain::{ + behaviour::{Conversion, ReverseConversion}, + merchant_key_store, + }, +}; + +#[async_trait::async_trait] +pub trait MerchantKeyStoreInterface { + async fn insert_merchant_key_store( + &self, + merchant_key_store: merchant_key_store::MerchantKeyStore, + ) -> CustomResult<merchant_key_store::MerchantKeyStore, errors::StorageError>; + + async fn get_merchant_key_store_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<merchant_key_store::MerchantKeyStore, errors::StorageError>; +} + +#[async_trait::async_trait] +impl MerchantKeyStoreInterface for Store { + async fn insert_merchant_key_store( + &self, + merchant_key_store: merchant_key_store::MerchantKeyStore, + ) -> CustomResult<merchant_key_store::MerchantKeyStore, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + let merchant_id = merchant_key_store.merchant_id.clone(); + merchant_key_store + .construct_new() + .await + .change_context(errors::StorageError::EncryptionError)? + .insert(&conn) + .await + .map_err(Into::into) + .into_report()? + .convert(self, &merchant_id) + .await + .change_context(errors::StorageError::DecryptionError) + } + async fn get_merchant_key_store_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<merchant_key_store::MerchantKeyStore, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id( + &conn, + merchant_id, + ) + .await + .map_err(Into::into) + .into_report()? + .convert(self, merchant_id) + .await + .change_context(errors::StorageError::DecryptionError) + } +} + +#[async_trait::async_trait] +impl MerchantKeyStoreInterface for MockDb { + async fn insert_merchant_key_store( + &self, + _merchant_key_store: merchant_key_store::MerchantKeyStore, + ) -> CustomResult<merchant_key_store::MerchantKeyStore, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError.into()) + } + async fn get_merchant_key_store_by_merchant_id( + &self, + _merchant_id: &str, + ) -> CustomResult<merchant_key_store::MerchantKeyStore, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError.into()) + } +} diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 133a01bb5cd..305cf5204ff 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -68,5 +68,9 @@ histogram_metric!(CARD_ADD_TIME, GLOBAL_METER); histogram_metric!(CARD_GET_TIME, GLOBAL_METER); histogram_metric!(CARD_DELETE_TIME, GLOBAL_METER); +// Encryption and Decryption metrics +histogram_metric!(ENCRYPTION_TIME, GLOBAL_METER); +histogram_metric!(DECRYPTION_TIME, GLOBAL_METER); + pub mod request; pub mod utils; diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs index 92f6d823784..a38ba471ebf 100644 --- a/crates/router/src/routes/metrics/request.rs +++ b/crates/router/src/routes/metrics/request.rs @@ -19,7 +19,7 @@ where } #[inline] -pub async fn record_card_operation_time<F, R>( +pub async fn record_operation_time<F, R>( future: F, metric: &once_cell::sync::Lazy<router_env::opentelemetry::metrics::Histogram<f64>>, ) -> R diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 74c4a71c6dc..587cce9c0d5 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -6,6 +6,8 @@ pub mod logger; use std::sync::{atomic, Arc}; use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "kms")] +use external_services::kms; use futures::StreamExt; use redis_interface::{errors as redis_errors, PubsubInterface}; @@ -80,6 +82,7 @@ pub struct Store { pub redis_conn: Arc<redis_interface::RedisConnectionPool>, #[cfg(feature = "kv_store")] pub(crate) config: StoreConfig, + pub master_key: Vec<u8>, } #[cfg(feature = "kv_store")] @@ -108,6 +111,13 @@ impl Store { redis_clone.on_error().await; }); + let master_enc_key = get_master_enc_key( + config, + #[cfg(feature = "kms")] + &config.kms, + ) + .await; + Self { master_pool: diesel_make_pg_pool( &config.master_database, @@ -130,6 +140,7 @@ impl Store { drainer_stream_name: config.drainer.stream_name.clone(), drainer_num_partitions: config.drainer.num_partitions, }, + master_key: master_enc_key, } } @@ -177,3 +188,37 @@ impl Store { .change_context(crate::core::errors::StorageError::KVError) } } + +#[allow(clippy::expect_used)] +async fn get_master_enc_key( + conf: &crate::configs::settings::Settings, + #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, +) -> Vec<u8> { + #[cfg(feature = "kms")] + let master_enc_key = hex::decode( + kms::get_kms_client(kms_config) + .await + .decrypt(&conf.secrets.master_enc_key) + .await + .expect("Failed to decrypt master enc key"), + ) + .expect("Failed to decode from hex"); + + #[cfg(not(feature = "kms"))] + let master_enc_key = + hex::decode(&conf.secrets.master_enc_key).expect("Failed to decode from hex"); + + master_enc_key +} + +#[inline] +pub fn generate_aes256_key() -> errors::CustomResult<[u8; 32], common_utils::errors::CryptoError> { + use ring::rand::SecureRandom; + + let rng = ring::rand::SystemRandom::new(); + let mut key: [u8; 256 / 8] = [0_u8; 256 / 8]; + rng.fill(&mut key) + .into_report() + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + Ok(key) +} diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs index 252cd63d6d0..0eb5b6118a0 100644 --- a/crates/router/src/types/domain.rs +++ b/crates/router/src/types/domain.rs @@ -3,4 +3,5 @@ pub mod behaviour; pub mod customer; pub mod merchant_account; pub mod merchant_connector_account; +pub mod merchant_key_store; pub mod types; diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index eebbff2b4f6..d69343cc798 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -12,6 +12,7 @@ use super::{ behaviour, types::{self, AsyncLift}, }; +use crate::db::StorageInterface; #[derive(Clone, Debug, serde::Serialize)] pub struct Address { @@ -69,11 +70,19 @@ impl behaviour::Conversion for Address { }) } - async fn convert_back(other: Self::DstType) -> CustomResult<Self, ValidationError> { - let key = &[0]; + async fn convert_back( + other: Self::DstType, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<Self, ValidationError> { + let key = types::get_merchant_enc_key(db, merchant_id) + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while getting key from key store".to_string(), + })?; async { - let inner_decrypt = |inner| types::decrypt(inner, key); + let inner_decrypt = |inner| types::decrypt(inner, &key); Ok(Self { id: Some(other.id), address_id: other.address_id, diff --git a/crates/router/src/types/domain/behaviour.rs b/crates/router/src/types/domain/behaviour.rs index 298c7c83e66..2f95fe1611c 100644 --- a/crates/router/src/types/domain/behaviour.rs +++ b/crates/router/src/types/domain/behaviour.rs @@ -1,5 +1,7 @@ use common_utils::errors::{CustomResult, ValidationError}; +use crate::db::StorageInterface; + /// Trait for converting domain types to storage models #[async_trait::async_trait] pub trait Conversion { @@ -7,7 +9,11 @@ pub trait Conversion { type NewDstType; async fn convert(self) -> CustomResult<Self::DstType, ValidationError>; - async fn convert_back(item: Self::DstType) -> CustomResult<Self, ValidationError> + async fn convert_back( + item: Self::DstType, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<Self, ValidationError> where Self: Sized; @@ -16,12 +22,20 @@ pub trait Conversion { #[async_trait::async_trait] pub trait ReverseConversion<SrcType: Conversion> { - async fn convert(self) -> CustomResult<SrcType, ValidationError>; + async fn convert( + self, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<SrcType, ValidationError>; } #[async_trait::async_trait] impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T { - async fn convert(self) -> CustomResult<U, ValidationError> { - U::convert_back(self).await + async fn convert( + self, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<U, ValidationError> { + U::convert_back(self, db, merchant_id).await } } diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index d4e4d2b26e4..ca812bd8869 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -7,7 +7,10 @@ use storage_models::{customers::CustomerUpdateInternal, encryption::Encryption}; use time::PrimitiveDateTime; use super::types::{self, AsyncLift}; -use crate::errors::{CustomResult, ValidationError}; +use crate::{ + db::StorageInterface, + errors::{CustomResult, ValidationError}, +}; #[derive(Clone, Debug)] pub struct Customer { @@ -44,14 +47,22 @@ impl super::behaviour::Conversion for Customer { }) } - async fn convert_back(item: Self::DstType) -> CustomResult<Self, ValidationError> + async fn convert_back( + item: Self::DstType, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<Self, ValidationError> where Self: Sized, { - let key = &[0]; // To be replaced by key fetched from Store + let key = types::get_merchant_enc_key(db, merchant_id) + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while getting key from key store".to_string(), + })?; async { - let inner_decrypt = |inner| types::decrypt(inner, key); - let inner_decrypt_email = |inner| types::decrypt(inner, key); + let inner_decrypt = |inner| types::decrypt(inner, &key); + let inner_decrypt_email = |inner| types::decrypt(inner, &key); Ok(Self { id: Some(item.id), customer_id: item.customer_id, diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rs index bd6f15d686b..76ab589889e 100644 --- a/crates/router/src/types/domain/merchant_account.rs +++ b/crates/router/src/types/domain/merchant_account.rs @@ -10,6 +10,7 @@ use storage_models::{ }; use crate::{ + db::StorageInterface, errors::{CustomResult, ValidationError}, types::domain::types::{self, AsyncLift, TypeEncryption}, }; @@ -126,11 +127,19 @@ impl super::behaviour::Conversion for MerchantAccount { }) } - async fn convert_back(item: Self::DstType) -> CustomResult<Self, ValidationError> + async fn convert_back( + item: Self::DstType, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<Self, ValidationError> where Self: Sized, { - let key = &[0]; + let key = types::get_merchant_enc_key(db, merchant_id.to_owned()) + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while getting key from key store".to_string(), + })?; async { Ok(Self { id: Some(item.id), @@ -141,11 +150,11 @@ impl super::behaviour::Conversion for MerchantAccount { redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item .merchant_name - .async_lift(|inner| types::decrypt(inner, key)) + .async_lift(|inner| types::decrypt(inner, &key)) .await?, merchant_details: item .merchant_details - .async_lift(|inner| types::decrypt(inner, key)) + .async_lift(|inner| types::decrypt(inner, &key)) .await?, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, @@ -157,7 +166,7 @@ impl super::behaviour::Conversion for MerchantAccount { routing_algorithm: item.routing_algorithm, api_key: item .api_key - .async_map(|value| Encryptable::decrypt(value, key, GcmAes256 {})) + .async_map(|value| Encryptable::decrypt(value, &key, GcmAes256 {})) .await .transpose()?, }) diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 84db026c43a..52ad4db926a 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -1,18 +1,27 @@ use common_utils::{ + crypto::{Encryptable, GcmAes256}, errors::{CustomResult, ValidationError}, pii, }; -use masking::{ExposeInterface, Secret}; -use storage_models::enums; +use error_stack::ResultExt; +use masking::Secret; +use storage_models::{ + encryption::Encryption, enums, + merchant_connector_account::MerchantConnectorAccountUpdateInternal, +}; -use super::behaviour; +use super::{ + behaviour, + types::{self, TypeEncryption}, +}; +use crate::db::StorageInterface; -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug)] pub struct MerchantConnectorAccount { pub id: Option<i32>, pub merchant_id: String, pub connector_name: String, - pub connector_account_details: Secret<serde_json::Value>, + pub connector_account_details: Encryptable<Secret<serde_json::Value>>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: String, @@ -21,6 +30,21 @@ pub struct MerchantConnectorAccount { pub metadata: Option<pii::SecretSerdeValue>, } +#[derive(Debug)] +pub enum MerchantConnectorAccountUpdate { + Update { + merchant_id: Option<String>, + connector_type: Option<enums::ConnectorType>, + connector_name: Option<String>, + connector_account_details: Option<Encryptable<Secret<serde_json::Value>>>, + test_mode: Option<bool>, + disabled: Option<bool>, + merchant_connector_id: Option<String>, + payment_methods_enabled: Option<Vec<serde_json::Value>>, + metadata: Option<pii::SecretSerdeValue>, + }, +} + #[async_trait::async_trait] impl behaviour::Conversion for MerchantConnectorAccount { type DstType = storage_models::merchant_connector_account::MerchantConnectorAccount; @@ -34,7 +58,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { })?, merchant_id: self.merchant_id, connector_name: self.connector_name, - connector_account_details: self.connector_account_details.expose(), + connector_account_details: self.connector_account_details.into(), test_mode: self.test_mode, disabled: self.disabled, merchant_connector_id: self.merchant_connector_id, @@ -45,12 +69,29 @@ impl behaviour::Conversion for MerchantConnectorAccount { ) } - async fn convert_back(other: Self::DstType) -> CustomResult<Self, ValidationError> { + async fn convert_back( + other: Self::DstType, + db: &dyn StorageInterface, + merchant_id: &str, + ) -> CustomResult<Self, ValidationError> { + let key = types::get_merchant_enc_key(db, merchant_id) + .await + .change_context(ValidationError::InvalidValue { + message: "Error while getting key from keystore".to_string(), + })?; Ok(Self { id: Some(other.id), merchant_id: other.merchant_id, connector_name: other.connector_name, - connector_account_details: other.connector_account_details.into(), + connector_account_details: Encryptable::decrypt( + other.connector_account_details, + &key, + GcmAes256 {}, + ) + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting connector account details".to_string(), + })?, test_mode: other.test_mode, disabled: other.disabled, merchant_connector_id: other.merchant_connector_id, @@ -64,7 +105,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { Ok(Self::NewDstType { merchant_id: Some(self.merchant_id), connector_name: Some(self.connector_name), - connector_account_details: Some(self.connector_account_details), + connector_account_details: Some(self.connector_account_details.into()), test_mode: self.test_mode, disabled: self.disabled, merchant_connector_id: self.merchant_connector_id, @@ -74,3 +115,31 @@ impl behaviour::Conversion for MerchantConnectorAccount { }) } } + +impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal { + fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self { + match merchant_connector_account_update { + MerchantConnectorAccountUpdate::Update { + merchant_id, + connector_type, + connector_name, + connector_account_details, + test_mode, + disabled, + merchant_connector_id, + payment_methods_enabled, + metadata, + } => Self { + merchant_id, + connector_type, + connector_name, + connector_account_details: connector_account_details.map(Encryption::from), + test_mode, + disabled, + merchant_connector_id, + payment_methods_enabled, + metadata, + }, + } + } +} diff --git a/crates/router/src/types/domain/merchant_key_store.rs b/crates/router/src/types/domain/merchant_key_store.rs new file mode 100644 index 00000000000..c4c0f4d830d --- /dev/null +++ b/crates/router/src/types/domain/merchant_key_store.rs @@ -0,0 +1,61 @@ +use common_utils::{ + crypto::{Encryptable, GcmAes256}, + custom_serde, +}; +use error_stack::ResultExt; +use masking::Secret; +use time::PrimitiveDateTime; + +use crate::{ + db::StorageInterface, + errors::{CustomResult, ValidationError}, + types::domain::types::TypeEncryption, +}; + +#[derive(Clone, Debug, serde::Serialize)] +pub struct MerchantKeyStore { + pub merchant_id: String, + pub key: Encryptable<Secret<Vec<u8>>>, + #[serde(with = "custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, +} + +#[async_trait::async_trait] +impl super::behaviour::Conversion for MerchantKeyStore { + type DstType = storage_models::merchant_key_store::MerchantKeyStore; + type NewDstType = storage_models::merchant_key_store::MerchantKeyStoreNew; + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(storage_models::merchant_key_store::MerchantKeyStore { + key: self.key.into(), + merchant_id: self.merchant_id, + created_at: self.created_at, + }) + } + + async fn convert_back( + item: Self::DstType, + db: &dyn StorageInterface, + _merchant_id: &str, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + let key = &db.get_master_key(); + Ok(Self { + key: Encryptable::decrypt(item.key, key, GcmAes256 {}) + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting customer data".to_string(), + })?, + merchant_id: item.merchant_id, + created_at: item.created_at, + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(storage_models::merchant_key_store::MerchantKeyStoreNew { + merchant_id: self.merchant_id, + key: self.key.into(), + }) + } +} diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs index ade0ecd9d96..80dab9d1b0f 100644 --- a/crates/router/src/types/domain/types.rs +++ b/crates/router/src/types/domain/types.rs @@ -5,10 +5,11 @@ use common_utils::{ ext_traits::AsyncExt, }; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; +use router_env::{instrument, tracing}; use storage_models::encryption::Encryption; -use crate::core::errors as core_errors; +use crate::routes::metrics::{request, DECRYPTION_TIME, ENCRYPTION_TIME}; #[async_trait] pub trait TypeEncryption< @@ -35,6 +36,7 @@ impl< S: masking::Strategy<String> + Send, > TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>> { + #[instrument(skip_all)] async fn encrypt( masked_data: Secret<String, S>, key: &[u8], @@ -45,6 +47,7 @@ impl< Ok(Self::new(masked_data, encrypted_data)) } + #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], @@ -68,6 +71,7 @@ impl< > TypeEncryption<serde_json::Value, V, S> for crypto::Encryptable<Secret<serde_json::Value, S>> { + #[instrument(skip_all)] async fn encrypt( masked_data: Secret<serde_json::Value, S>, key: &[u8], @@ -81,6 +85,7 @@ impl< Ok(Self::new(masked_data, encrypted_data)) } + #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], @@ -96,11 +101,47 @@ impl< } } -pub async fn get_key_and_algo( - _db: &dyn crate::db::StorageInterface, - _merchant_id: String, -) -> CustomResult<Vec<u8>, core_errors::StorageError> { - Ok(Vec::new()) +#[async_trait] +impl< + V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, + S: masking::Strategy<Vec<u8>> + Send, + > TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>> +{ + #[instrument(skip_all)] + async fn encrypt( + masked_data: Secret<Vec<u8>, S>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?; + + Ok(Self::new(masked_data, encrypted_data)) + } + + #[instrument(skip_all)] + async fn decrypt( + encrypted_data: Encryption, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + let encrypted = encrypted_data.into_inner(); + let decrypted_data = crypt_algo.decode_message(key, encrypted.clone())?; + + Ok(Self::new(decrypted_data.into(), encrypted)) + } +} + +pub async fn get_merchant_enc_key( + db: &dyn crate::db::StorageInterface, + merchant_id: impl AsRef<str>, +) -> CustomResult<Vec<u8>, crate::core::errors::StorageError> { + let merchant_id = merchant_id.as_ref(); + let key = db + .get_merchant_key_store_by_merchant_id(merchant_id) + .await? + .key + .into_inner(); + Ok(key.expose()) } pub trait Lift<U> { @@ -149,6 +190,21 @@ impl<U, V: Lift<U> + Lift<U, SelfWrapper<U> = V> + Send> AsyncLift<U> for V { } } +pub(crate) async fn encrypt<E: Clone, S>( + inner: Secret<E, S>, + key: &[u8], +) -> CustomResult<crypto::Encryptable<Secret<E, S>>, errors::CryptoError> +where + S: masking::Strategy<E>, + crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, +{ + request::record_operation_time( + crypto::Encryptable::encrypt(inner, key, crypto::GcmAes256 {}), + &ENCRYPTION_TIME, + ) + .await +} + pub(crate) async fn decrypt<T: Clone, S: masking::Strategy<T>>( inner: Option<Encryption>, key: &[u8], @@ -156,8 +212,10 @@ pub(crate) async fn decrypt<T: Clone, S: masking::Strategy<T>>( where crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { - inner - .async_map(|item| crypto::Encryptable::decrypt(item, key, crypto::GcmAes256 {})) - .await - .transpose() + request::record_operation_time( + inner.async_map(|item| crypto::Encryptable::decrypt(item, key, crypto::GcmAes256 {})), + &DECRYPTION_TIME, + ) + .await + .transpose() } diff --git a/crates/router/src/types/storage/merchant_connector_account.rs b/crates/router/src/types/storage/merchant_connector_account.rs index 249538f5823..700a97048a9 100644 --- a/crates/router/src/types/storage/merchant_connector_account.rs +++ b/crates/router/src/types/storage/merchant_connector_account.rs @@ -1,4 +1,5 @@ pub use storage_models::merchant_connector_account::{ - MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdate, - MerchantConnectorAccountUpdateInternal, + MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdateInternal, }; + +pub use crate::types::domain::merchant_connector_account::MerchantConnectorAccountUpdate; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 2f387f26509..f4d8a70f817 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -332,7 +332,7 @@ impl TryFrom<domain::merchant_connector_account::MerchantConnectorAccount> connector_type: merchant_ca.connector_type.foreign_into(), connector_name: merchant_ca.connector_name, merchant_connector_id: Some(merchant_ca.merchant_connector_id), - connector_account_details: Some(merchant_ca.connector_account_details), + connector_account_details: Some(merchant_ca.connector_account_details.into_inner()), test_mode: merchant_ca.test_mode, disabled: merchant_ca.disabled, metadata: merchant_ca.metadata, diff --git a/crates/storage_models/src/encryption.rs b/crates/storage_models/src/encryption.rs index e0d9e054f21..a32dd45682e 100644 --- a/crates/storage_models/src/encryption.rs +++ b/crates/storage_models/src/encryption.rs @@ -1,4 +1,9 @@ -use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types, AsExpression}; +use diesel::{ + backend::Backend, + deserialize::{self, FromSql, Queryable}, + serialize::ToSql, + sql_types, AsExpression, +}; #[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize)] #[diesel(sql_type = diesel::sql_types::Binary)] @@ -51,3 +56,14 @@ where self.get_inner().to_sql(out) } } + +impl<DB> Queryable<sql_types::Binary, DB> for Encryption +where + DB: Backend, + Vec<u8>: FromSql<sql_types::Binary, DB>, +{ + type Row = Vec<u8>; + fn build(row: Self::Row) -> deserialize::Result<Self> { + Ok(Self { inner: row }) + } +} diff --git a/crates/storage_models/src/lib.rs b/crates/storage_models/src/lib.rs index 4598f4db145..59eed2c9684 100644 --- a/crates/storage_models/src/lib.rs +++ b/crates/storage_models/src/lib.rs @@ -16,6 +16,7 @@ pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; +pub mod merchant_key_store; pub mod payment_attempt; pub mod payment_intent; pub mod payment_method; diff --git a/crates/storage_models/src/merchant_connector_account.rs b/crates/storage_models/src/merchant_connector_account.rs index 08d3fa21fa3..189dd0770f6 100644 --- a/crates/storage_models/src/merchant_connector_account.rs +++ b/crates/storage_models/src/merchant_connector_account.rs @@ -1,16 +1,13 @@ use common_utils::pii; use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; -use masking::Secret; -use crate::{enums as storage_enums, schema::merchant_connector_account}; +use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_connector_account}; #[derive( Clone, Debug, - Eq, serde::Serialize, serde::Deserialize, - PartialEq, Identifiable, Queryable, router_derive::DebugAsDisplay, @@ -20,7 +17,7 @@ pub struct MerchantConnectorAccount { pub id: i32, pub merchant_id: String, pub connector_name: String, - pub connector_account_details: serde_json::Value, + pub connector_account_details: Encryption, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: String, @@ -36,7 +33,7 @@ pub struct MerchantConnectorAccountNew { pub merchant_id: Option<String>, pub connector_type: Option<storage_enums::ConnectorType>, pub connector_name: Option<String>, - pub connector_account_details: Option<Secret<serde_json::Value>>, + pub connector_account_details: Option<Encryption>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: String, @@ -44,58 +41,16 @@ pub struct MerchantConnectorAccountNew { pub metadata: Option<pii::SecretSerdeValue>, } -#[derive(Debug)] -pub enum MerchantConnectorAccountUpdate { - Update { - merchant_id: Option<String>, - connector_type: Option<storage_enums::ConnectorType>, - connector_name: Option<String>, - connector_account_details: Option<Secret<serde_json::Value>>, - test_mode: Option<bool>, - disabled: Option<bool>, - merchant_connector_id: Option<String>, - payment_methods_enabled: Option<Vec<serde_json::Value>>, - metadata: Option<pii::SecretSerdeValue>, - }, -} #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountUpdateInternal { - merchant_id: Option<String>, - connector_type: Option<storage_enums::ConnectorType>, - connector_name: Option<String>, - connector_account_details: Option<Secret<serde_json::Value>>, - test_mode: Option<bool>, - disabled: Option<bool>, - merchant_connector_id: Option<String>, - payment_methods_enabled: Option<Vec<serde_json::Value>>, - metadata: Option<pii::SecretSerdeValue>, -} - -impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal { - fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self { - match merchant_connector_account_update { - MerchantConnectorAccountUpdate::Update { - merchant_id, - connector_type, - connector_name, - connector_account_details, - test_mode, - disabled, - merchant_connector_id, - payment_methods_enabled, - metadata, - } => Self { - merchant_id, - connector_type, - connector_name, - connector_account_details, - test_mode, - disabled, - merchant_connector_id, - payment_methods_enabled, - metadata, - }, - } - } + pub merchant_id: Option<String>, + pub connector_type: Option<storage_enums::ConnectorType>, + pub connector_name: Option<String>, + pub connector_account_details: Option<Encryption>, + pub test_mode: Option<bool>, + pub disabled: Option<bool>, + pub merchant_connector_id: Option<String>, + pub payment_methods_enabled: Option<Vec<serde_json::Value>>, + pub metadata: Option<pii::SecretSerdeValue>, } diff --git a/crates/storage_models/src/merchant_key_store.rs b/crates/storage_models/src/merchant_key_store.rs new file mode 100644 index 00000000000..90d24f5b932 --- /dev/null +++ b/crates/storage_models/src/merchant_key_store.rs @@ -0,0 +1,41 @@ +use common_utils::custom_serde; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use time::PrimitiveDateTime; + +use crate::{encryption::Encryption, schema::merchantkeystore}; + +#[derive( + Clone, + Debug, + serde::Serialize, + serde::Deserialize, + Identifiable, + Queryable, + router_derive::DebugAsDisplay, +)] +#[diesel(table_name = merchantkeystore)] +#[diesel(primary_key(merchant_id))] +pub struct MerchantKeyStore { + pub merchant_id: String, + pub key: Encryption, + #[serde(with = "custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, +} + +#[derive( + Clone, Debug, serde::Serialize, serde::Deserialize, Insertable, router_derive::DebugAsDisplay, +)] +#[diesel(table_name = merchantkeystore)] +pub struct MerchantKeyStoreNew { + pub merchant_id: String, + pub key: Encryption, +} + +#[derive( + Clone, Debug, serde::Serialize, serde::Deserialize, AsChangeset, router_derive::DebugAsDisplay, +)] +#[diesel(table_name = merchantkeystore)] +pub struct MerchantKeyStoreUpdateInternal { + pub merchant_id: String, + pub key: Encryption, +} diff --git a/crates/storage_models/src/query.rs b/crates/storage_models/src/query.rs index 83baa4502c2..271bf9e1aef 100644 --- a/crates/storage_models/src/query.rs +++ b/crates/storage_models/src/query.rs @@ -11,6 +11,7 @@ pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; +pub mod merchant_key_store; pub mod payment_attempt; pub mod payment_intent; pub mod payment_method; diff --git a/crates/storage_models/src/query/merchant_connector_account.rs b/crates/storage_models/src/query/merchant_connector_account.rs index 6e63cdf6e66..18aab8a0802 100644 --- a/crates/storage_models/src/query/merchant_connector_account.rs +++ b/crates/storage_models/src/query/merchant_connector_account.rs @@ -5,7 +5,7 @@ use super::generics; use crate::{ errors, merchant_connector_account::{ - MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdate, + MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdateInternal, }, schema::merchant_connector_account::dsl, @@ -24,12 +24,12 @@ impl MerchantConnectorAccount { pub async fn update( self, conn: &PgPooledConn, - merchant_connector_account: MerchantConnectorAccountUpdate, + merchant_connector_account: MerchantConnectorAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.id, - MerchantConnectorAccountUpdateInternal::from(merchant_connector_account), + merchant_connector_account, ) .await { diff --git a/crates/storage_models/src/query/merchant_key_store.rs b/crates/storage_models/src/query/merchant_key_store.rs new file mode 100644 index 00000000000..e681c8c1dff --- /dev/null +++ b/crates/storage_models/src/query/merchant_key_store.rs @@ -0,0 +1,30 @@ +use diesel::{associations::HasTable, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + merchant_key_store::{MerchantKeyStore, MerchantKeyStoreNew}, + schema::merchantkeystore::dsl, + PgPooledConn, StorageResult, +}; + +impl MerchantKeyStoreNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantKeyStore> { + generics::generic_insert(conn, self).await + } +} + +impl MerchantKeyStore { + #[instrument(skip(conn))] + pub async fn find_by_merchant_id( + conn: &PgPooledConn, + merchant_id: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id.eq(merchant_id.to_owned()), + ) + .await + } +} diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 340c602efe2..06bb2163c52 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -9,14 +9,14 @@ diesel::table! { address_id -> Varchar, city -> Nullable<Varchar>, country -> Nullable<CountryCode>, - line1 -> Nullable<Binary>, - line2 -> Nullable<Binary>, - line3 -> Nullable<Binary>, - state -> Nullable<Binary>, - zip -> Nullable<Binary>, - first_name -> Nullable<Binary>, - last_name -> Nullable<Binary>, - phone_number -> Nullable<Binary>, + line1 -> Nullable<Bytea>, + line2 -> Nullable<Bytea>, + line3 -> Nullable<Bytea>, + state -> Nullable<Bytea>, + zip -> Nullable<Bytea>, + first_name -> Nullable<Bytea>, + last_name -> Nullable<Bytea>, + phone_number -> Nullable<Bytea>, country_code -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, @@ -99,9 +99,9 @@ diesel::table! { id -> Int4, customer_id -> Varchar, merchant_id -> Varchar, - name -> Nullable<Binary>, - email -> Nullable<Binary>, - phone -> Nullable<Binary>, + name -> Nullable<Bytea>, + email -> Nullable<Bytea>, + phone -> Nullable<Bytea>, phone_country_code -> Nullable<Varchar>, description -> Nullable<Varchar>, created_at -> Timestamp, @@ -212,8 +212,8 @@ diesel::table! { enable_payment_response_hash -> Bool, payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, - merchant_name -> Nullable<Binary>, - merchant_details -> Nullable<Binary>, + merchant_name -> Nullable<Bytea>, + merchant_details -> Nullable<Bytea>, webhook_details -> Nullable<Json>, sub_merchants_enabled -> Nullable<Bool>, parent_merchant_id -> Nullable<Varchar>, @@ -222,7 +222,7 @@ diesel::table! { locker_id -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, routing_algorithm -> Nullable<Json>, - api_key -> Nullable<Binary>, + api_key -> Nullable<Bytea>, } } @@ -234,7 +234,7 @@ diesel::table! { id -> Int4, merchant_id -> Varchar, connector_name -> Varchar, - connector_account_details -> Json, + connector_account_details -> Bytea, test_mode -> Nullable<Bool>, disabled -> Nullable<Bool>, merchant_connector_id -> Varchar, @@ -244,6 +244,17 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + merchantkeystore (merchant_id) { + merchant_id -> Varchar, + key -> Bytea, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -423,6 +434,7 @@ diesel::allow_tables_to_appear_in_same_query!( mandate, merchant_account, merchant_connector_account, + merchantkeystore, payment_attempt, payment_intent, payment_methods, diff --git a/migrations/2023-04-06-092008_create_merchant_ek/down.sql b/migrations/2023-04-06-092008_create_merchant_ek/down.sql new file mode 100644 index 00000000000..de0fb814836 --- /dev/null +++ b/migrations/2023-04-06-092008_create_merchant_ek/down.sql @@ -0,0 +1 @@ +DROP TABLE MERCHANTKEYSTORE; diff --git a/migrations/2023-04-06-092008_create_merchant_ek/up.sql b/migrations/2023-04-06-092008_create_merchant_ek/up.sql new file mode 100644 index 00000000000..3703f68b937 --- /dev/null +++ b/migrations/2023-04-06-092008_create_merchant_ek/up.sql @@ -0,0 +1,7 @@ +CREATE TABLE MERCHANTKEYSTORE( + MERCHANT_ID VARCHAR(255) NOT NULL PRIMARY KEY, + KEY BYTEA NOT NULL, + CREATED_AT TIMESTAMP NOT NULL DEFAULT now() +); + +CREATE UNIQUE INDEX merchant_key_store_unique_index ON merchantkeystore(merchant_id);
2023-04-13T09:59:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> This PR adds key store DB which stores encryption key per merchant account. The encryption key will be further encrypted by `master_key` which will further be KMS encrypted. ### Additional Changes - [x] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
a8e45bb718d4a6fe44ae5ad938bfd6d239447ebd
juspay/hyperswitch
juspay__hyperswitch-5117
Bug: update last used when the customer acceptance is passed in the recurring payment We need to update the last used for a payment method as whenever a payment is done with that particular saved payment method. Currently we if a customer is making a payment (CIT) with the payment data that is same as the one that is already saved we are not updating the last used a for the payment method in the db. In this case the new CIT with the payment_data that is same as the one saved also needs to be tied to the saved pm and the last used for it needs to be updated.
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index d9c7a66a6b2..16e8ddeb7d5 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -96,8 +96,13 @@ pub struct TokenizeCoreWorkflow { #[derive(Debug, Serialize, Deserialize)] pub enum PaymentMethodUpdate { - MetadataUpdate { + MetadataUpdateAndLastUsed { metadata: Option<serde_json::Value>, + last_used_at: PrimitiveDateTime, + }, + UpdatePaymentMethodDataAndLastUsed { + payment_method_data: Option<Encryption>, + last_used_at: PrimitiveDateTime, }, PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, @@ -191,10 +196,13 @@ impl PaymentMethodUpdateInternal { impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { fn from(payment_method_update: PaymentMethodUpdate) -> Self { match payment_method_update { - PaymentMethodUpdate::MetadataUpdate { metadata } => Self { + PaymentMethodUpdate::MetadataUpdateAndLastUsed { + metadata, + last_used_at, + } => Self { metadata, payment_method_data: None, - last_used_at: None, + last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, @@ -232,6 +240,22 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { payment_method_issuer: None, payment_method_type: None, }, + PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { + payment_method_data, + last_used_at, + } => Self { + metadata: None, + payment_method_data, + last_used_at: Some(last_used_at), + network_transaction_id: None, + status: None, + locker_id: None, + payment_method: None, + connector_mandate_details: None, + updated_by: None, + payment_method_issuer: None, + payment_method_type: None, + }, PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 53b0063c6ef..04137b53c87 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1389,14 +1389,31 @@ pub async fn call_to_locker_hs<'a>( Ok(stored_card) } -pub async fn update_payment_method( +pub async fn update_payment_method_metadata_and_last_used( db: &dyn db::StorageInterface, pm: payment_method::PaymentMethod, - pm_metadata: serde_json::Value, + pm_metadata: Option<serde_json::Value>, + storage_scheme: MerchantStorageScheme, +) -> errors::CustomResult<(), errors::VaultError> { + let pm_update = payment_method::PaymentMethodUpdate::MetadataUpdateAndLastUsed { + metadata: pm_metadata, + last_used_at: common_utils::date_time::now(), + }; + db.update_payment_method(pm, pm_update, storage_scheme) + .await + .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?; + Ok(()) +} + +pub async fn update_payment_method_and_last_used( + db: &dyn db::StorageInterface, + pm: payment_method::PaymentMethod, + payment_method_update: Option<Encryption>, storage_scheme: MerchantStorageScheme, ) -> errors::CustomResult<(), errors::VaultError> { - let pm_update = payment_method::PaymentMethodUpdate::MetadataUpdate { - metadata: Some(pm_metadata), + let pm_update = payment_method::PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { + payment_method_data: payment_method_update, + last_used_at: common_utils::date_time::now(), }; db.update_payment_method(pm, pm_update, storage_scheme) .await diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index c4e4cb694e6..8fb0964da6e 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -114,9 +114,14 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor .get_payment_method_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|address| address.get_optional_full_name()); + let mut should_avoid_saving = false; if let Some(payment_method_info) = &payment_data.payment_method_info { if payment_data.payment_intent.off_session.is_none() && resp.response.is_ok() { + should_avoid_saving = resp.request.payment_method_type + == Some(enums::PaymentMethodType::ApplePay) + || resp.request.payment_method_type + == Some(enums::PaymentMethodType::GooglePay); payment_methods::cards::update_last_used_at( payment_method_info, state, @@ -179,6 +184,12 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor let (payment_method_id, _payment_method_status) = save_payment_call_future.await?; payment_data.payment_attempt.payment_method_id = payment_method_id; Ok(()) + } else if should_avoid_saving { + if let Some(pm_info) = &payment_data.payment_method_info { + payment_data.payment_attempt.payment_method_id = + Some(pm_info.payment_method_id.clone()); + }; + Ok(()) } else { // Save card flow let save_payment_data = tokenization::SavePaymentMethodData::from(resp); diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 161a9a43532..619d74549e7 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -269,20 +269,15 @@ where pm.metadata.as_ref(), connector_token, )?; - if let Some(metadata) = pm_metadata { - payment_methods::cards::update_payment_method( - db, - pm.clone(), - metadata, - merchant_account.storage_scheme, - ) - .await - .change_context( - errors::ApiErrorResponse::InternalServerError, - ) - .attach_printable("Failed to add payment method in db")?; - }; - // update if its a off-session mit payment + payment_methods::cards::update_payment_method_metadata_and_last_used( + db, + pm.clone(), + pm_metadata, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; if check_for_mit_mandates { let connector_mandate_details = update_connector_mandate_details_in_payment_method( @@ -511,14 +506,10 @@ where ) .await; - let pm_update = - storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: pm_data_encrypted, - }; - - db.update_payment_method( + payment_methods::cards::update_payment_method_and_last_used( + db, existing_pm, - pm_update, + pm_data_encrypted, merchant_account.storage_scheme, ) .await @@ -528,7 +519,7 @@ where } }, None => { - let customer_saved_pm_id_option = if payment_method_type + let customer_saved_pm_option = if payment_method_type == Some(api_models::enums::PaymentMethodType::ApplePay) || payment_method_type == Some(api_models::enums::PaymentMethodType::GooglePay) @@ -547,7 +538,7 @@ where .find(|payment_method| { payment_method.payment_method_type == payment_method_type }) - .map(|pm| pm.payment_method_id.clone())), + .cloned()), Err(error) => { if error.current_context().is_db_not_found() { Ok(None) @@ -566,8 +557,18 @@ where Ok(None) }?; - if let Some(customer_saved_pm_id) = customer_saved_pm_id_option { - resp.payment_method_id = customer_saved_pm_id; + if let Some(customer_saved_pm) = customer_saved_pm_option { + payment_methods::cards::update_last_used_at( + &customer_saved_pm, + state, + merchant_account.storage_scheme, + ) + .await + .map_err(|e| { + logger::error!("Failed to update last used at: {:?}", e); + }) + .ok(); + resp.payment_method_id = customer_saved_pm.payment_method_id; } else { let pm_metadata = create_payment_method_metadata(None, connector_token)?;
2024-06-25T11:49:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We need to update the last used for a payment method as whenever a payment is done with that particular saved payment method. Currently we if a customer is making a payment (CIT) with the payment data that is same as the one that is already saved we are not updating the last used a for the payment method in the db. In this case the new CIT with the payment_data that is same as the one saved also needs to be tied to the saved pm and the last used for it needs to be updated. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create mca -> Save card for customer with setup_future_usage offsession ``` { "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "{{$timestamp}}", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "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": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "sai harsha", "card_cvc": "737" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "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": "John", "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": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` <img width="1083" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f4d7a58a-5c2d-4686-a669-22dc813fb546"> -> Add a one more payment method for the same customer ``` { "amount": 800, "currency": "USD", "confirm": true, "amount_to_capture": 800, "customer_id": "1719920836", "payment_type": "new_mandate", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "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" } }, "connector_metadata": { "noon": { "order_category": "pay" } } } ``` <img width="1021" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f808e595-4827-425f-9aa1-701b0d6b2b28"> -> Do payment method list for the customer ``` curl --location 'http://localhost:8080/customers/1719920836/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key:' ``` <img width="1028" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/cf96e878-b109-4313-ab7f-b15ab72da3d9"> -> The above result will display the apple pay on the top as it is recently added -> Now make a payment with the saved card ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_2k0GtUf0vXE48EFiTyUt9BBpuVp3Ir4BllhjCYff5hEkBMoEtpLxhmOekQabpit5' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 800, "currency": "USD", "confirm": false, "amount_to_capture": 800, "customer_id": "1719920836", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "setup_future_usage": "off_session" }' ``` <img width="1115" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/05abf536-d99f-40d4-a63f-214f40448983"> ``` curl --location 'http://localhost:8080/payments/pay_rD3KvlEfGmMOWfdm6GF7/confirm' \ --header 'api-key: pk_dev_a2a54e7ab646435f8ab94e791a8d273e' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_VV4tgEfPHNvgSkuEZWlN", "payment_method": "card", "client_secret": "pay_rD3KvlEfGmMOWfdm6GF7_secret_5fe0LNQ4eHIFbd8wz8CH" }' ``` <img width="1097" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c12f8199-fc0b-4cfd-8c90-5d9bcf205c25"> -> Do payment method list for the customer and the card should appear at the top ``` curl --location 'http://localhost:8080/customers/1719920836/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_2k0GtUf0vXE48EFiTyUt9BBpuVp3Ir4BllhjCYff5hEkBMoEtpLxhmOekQabpit5' ``` <img width="1138" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a09e4ddf-35fc-4e24-93e8-a9c421347d56"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ffe90a41125a0eb1e8a858b336120e355fd3b69e
juspay/hyperswitch
juspay__hyperswitch-5119
Bug: feat(email): Send `auth_id` in email URLs Currently links in the emails point to public dashboard. For SSO tenants/orgs, they should point to different url, which has `auth_id`.
diff --git a/config/config.example.toml b/config/config.example.toml index f29876e648b..10f8ba7a5e7 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -346,7 +346,6 @@ wildcard_origin = false # If true, allows any origin to make req [email] sender_email = "example@example.com" # Sender email aws_region = "" # AWS region used by AWS SES -base_url = "" # Base url used when adding links that should redirect to self allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email active_email_client = "SES" # The currently active email client @@ -359,6 +358,7 @@ sts_role_session_name = "" # An identifier for the assumed role session, used to password_validity_in_days = 90 # Number of days after which password should be updated two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside totp_issuer_name = "Hyperswitch" # Name of the issuer for TOTP +base_url = "" # Base url used for user specific redirects and emails #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 652b4950316..68df3d28e24 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -58,7 +58,6 @@ wildcard_origin = false # If true, allows any origin to make req [email] sender_email = "example@example.com" # Sender email aws_region = "" # AWS region used by AWS SES -base_url = "" # Dashboard base url used when adding links that should redirect to self, say https://app.hyperswitch.io for example allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email active_email_client = "SES" # The currently active email client diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index f5f69568da6..b75062c9340 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -118,6 +118,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Integ" +base_url = "https://integ.hyperswitch.io" [frm] enabled = true diff --git a/config/deployments/production.toml b/config/deployments/production.toml index bbaf22067b5..98008212fc0 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -125,6 +125,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Production" +base_url = "https://live.hyperswitch.io" [frm] enabled = false diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index de274ad9411..040986f7948 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -125,6 +125,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Sandbox" +base_url = "https://app.hyperswitch.io" [frm] enabled = true diff --git a/config/development.toml b/config/development.toml index 4e230cd2025..ecece79a696 100644 --- a/config/development.toml +++ b/config/development.toml @@ -264,7 +264,6 @@ wildcard_origin = true [email] sender_email = "example@example.com" aws_region = "" -base_url = "http://localhost:8080" allowed_unverified_days = 1 active_email_client = "SES" @@ -276,6 +275,7 @@ sts_role_session_name = "" password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Dev" +base_url = "http://localhost:8080" [bank_config.eps] stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 791f2510824..643893c7cb2 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -56,6 +56,7 @@ recon_admin_api_key = "recon_test_admin" password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch" +base_url = "http://localhost:8080" [locker] host = "" diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 6d567e7dca1..0006afea0d9 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -355,3 +355,8 @@ pub struct AuthMethodDetails { pub auth_type: common_enums::UserAuthType, pub name: Option<OpenIdProvider>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct AuthIdQueryParam { + pub auth_id: Option<String>, +} diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs index 07552cb519f..fc577a012c3 100644 --- a/crates/external_services/src/email.rs +++ b/crates/external_services/src/email.rs @@ -126,9 +126,6 @@ pub struct EmailSettings { /// The AWS region to send SES requests to. pub aws_region: String, - /// Base-url used when adding links that should redirect to self - pub base_url: String, - /// Number of days for verification of the email pub allowed_unverified_days: i64, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 80756391741..0569c4dbed6 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -484,6 +484,7 @@ pub struct UserSettings { pub password_validity_in_days: u16, pub two_factor_auth_expiry_in_secs: i64, pub totp_issuer_name: String, + pub base_url: String, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 505cee0c4ac..0fd583143cc 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -39,6 +39,7 @@ pub mod sample_data; pub async fn signup_with_merchant_id( state: SessionState, request: user_api::SignUpWithMerchantIdRequest, + auth_id: Option<String>, ) -> UserResponse<user_api::SignUpWithMerchantIdResponse> { let new_user = domain::NewUser::try_from(request.clone())?; new_user @@ -64,6 +65,7 @@ pub async fn signup_with_merchant_id( user_name: domain::UserName::new(user_from_db.get_name())?, settings: state.conf.clone(), subject: "Get back to Hyperswitch - Reset Your Password Now", + auth_id, }; let send_email_result = state @@ -241,6 +243,7 @@ pub async fn signin_token_only_flow( pub async fn connect_account( state: SessionState, request: user_api::ConnectAccountRequest, + auth_id: Option<String>, ) -> UserResponse<user_api::ConnectAccountResponse> { let find_user = state.global_store.find_user_by_email(&request.email).await; @@ -253,6 +256,7 @@ pub async fn connect_account( settings: state.conf.clone(), user_name: domain::UserName::new(user_from_db.get_name())?, subject: "Unlock Hyperswitch: Use Your Magic Link to Sign In", + auth_id, }; let send_email_result = state @@ -303,6 +307,7 @@ pub async fn connect_account( recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), subject: "Welcome to the Hyperswitch community!", + auth_id, }; let send_email_result = state @@ -401,6 +406,7 @@ pub async fn change_password( pub async fn forgot_password( state: SessionState, request: user_api::ForgotPasswordRequest, + auth_id: Option<String>, ) -> UserResponse<()> { let user_email = domain::UserEmail::from_pii_email(request.email)?; @@ -422,6 +428,7 @@ pub async fn forgot_password( settings: state.conf.clone(), user_name: domain::UserName::new(user_from_db.get_name())?, subject: "Get back to Hyperswitch - Reset Your Password Now", + auth_id, }; state @@ -596,6 +603,7 @@ pub async fn invite_multiple_user( requests: Vec<user_api::InviteUserRequest>, req_state: ReqState, is_token_only: Option<bool>, + auth_id: Option<String>, ) -> UserResponse<Vec<InviteMultipleUserResponse>> { if requests.len() > 10 { return Err(report!(UserErrors::MaxInvitationsError)) @@ -603,7 +611,15 @@ pub async fn invite_multiple_user( } let responses = futures::future::join_all(requests.iter().map(|request| async { - match handle_invitation(&state, &user_from_token, request, &req_state, is_token_only).await + match handle_invitation( + &state, + &user_from_token, + request, + &req_state, + is_token_only, + &auth_id, + ) + .await { Ok(response) => response, Err(error) => InviteMultipleUserResponse { @@ -625,6 +641,7 @@ async fn handle_invitation( request: &user_api::InviteUserRequest, req_state: &ReqState, is_token_only: Option<bool>, + auth_id: &Option<String>, ) -> UserResult<InviteMultipleUserResponse> { let inviter_user = user_from_token.get_user_from_db(state).await?; @@ -656,7 +673,14 @@ async fn handle_invitation( .await; if let Ok(invitee_user) = invitee_user { - handle_existing_user_invitation(state, user_from_token, request, invitee_user.into()).await + handle_existing_user_invitation( + state, + user_from_token, + request, + invitee_user.into(), + auth_id, + ) + .await } else if invitee_user .as_ref() .map_err(|e| e.current_context().is_db_not_found()) @@ -669,6 +693,7 @@ async fn handle_invitation( request, req_state.clone(), is_token_only, + auth_id, ) .await } else { @@ -676,12 +701,13 @@ async fn handle_invitation( } } -//TODO: send email +#[allow(unused_variables)] async fn handle_existing_user_invitation( state: &SessionState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, invitee_user_from_db: domain::UserFromStorage, + auth_id: &Option<String>, ) -> UserResult<InviteMultipleUserResponse> { let now = common_utils::date_time::now(); state @@ -722,6 +748,7 @@ async fn handle_existing_user_invitation( settings: state.conf.clone(), subject: "You have been invited to join Hyperswitch Community!", merchant_id: user_from_token.merchant_id.clone(), + auth_id: auth_id.clone(), }; is_email_sent = state @@ -748,12 +775,14 @@ async fn handle_existing_user_invitation( }) } +#[allow(unused_variables)] async fn handle_new_user_invitation( state: &SessionState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, req_state: ReqState, is_token_only: Option<bool>, + auth_id: &Option<String>, ) -> UserResult<InviteMultipleUserResponse> { let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?; @@ -809,6 +838,7 @@ async fn handle_new_user_invitation( settings: state.conf.clone(), subject: "You have been invited to join Hyperswitch Community!", merchant_id: user_from_token.merchant_id.clone(), + auth_id: auth_id.clone(), }) } else { Box::new(email_types::InviteUser { @@ -817,6 +847,7 @@ async fn handle_new_user_invitation( settings: state.conf.clone(), subject: "You have been invited to join Hyperswitch Community!", merchant_id: user_from_token.merchant_id.clone(), + auth_id: auth_id.clone(), }) }; let send_email_result = state @@ -862,7 +893,7 @@ pub async fn resend_invite( state: SessionState, user_from_token: auth::UserFromToken, request: user_api::ReInviteUserRequest, - _req_state: ReqState, + auth_id: Option<String>, ) -> UserResponse<()> { let invitee_email = domain::UserEmail::from_pii_email(request.email)?; let user: domain::UserFromStorage = state @@ -906,6 +937,7 @@ pub async fn resend_invite( settings: state.conf.clone(), subject: "You have been invited to join Hyperswitch Community!", merchant_id: user_from_token.merchant_id, + auth_id, }; state .email_client @@ -1518,6 +1550,7 @@ pub async fn verify_email_token_only_flow( pub async fn send_verification_mail( state: SessionState, req: user_api::SendVerifyEmailRequest, + auth_id: Option<String>, ) -> UserResponse<()> { let user_email = domain::UserEmail::try_from(req.email)?; let user = state @@ -1540,6 +1573,7 @@ pub async fn send_verification_mail( recipient_email: domain::UserEmail::from_pii_email(user.email)?, settings: state.conf.clone(), subject: "Welcome to the Hyperswitch community!", + auth_id, }; state diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index f297e41e4e0..816e7f7e2f8 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -39,15 +39,19 @@ pub async fn user_signup_with_merchant_id( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SignUpWithMerchantIdRequest>, + query: web::Query<user_api::AuthIdQueryParam>, ) -> HttpResponse { let flow = Flow::UserSignUpWithMerchantId; let req_payload = json_payload.into_inner(); + let auth_id = query.into_inner().auth_id; Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), - |state, _, req_body, _| user_core::signup_with_merchant_id(state, req_body), + |state, _, req_body, _| { + user_core::signup_with_merchant_id(state, req_body, auth_id.clone()) + }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) @@ -113,15 +117,17 @@ pub async fn user_connect_account( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::ConnectAccountRequest>, + query: web::Query<user_api::AuthIdQueryParam>, ) -> HttpResponse { let flow = Flow::UserConnectAccount; let req_payload = json_payload.into_inner(); + let auth_id = query.into_inner().auth_id; Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), - |state, _, req_body, _| user_core::connect_account(state, req_body), + |state, _, req_body, _| user_core::connect_account(state, req_body, auth_id.clone()), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -382,14 +388,16 @@ pub async fn forgot_password( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::ForgotPasswordRequest>, + query: web::Query<user_api::AuthIdQueryParam>, ) -> HttpResponse { let flow = Flow::ForgotPassword; + let auth_id = query.into_inner().auth_id; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), - |state, _, payload, _| user_core::forgot_password(state, payload), + |state, _, payload, _| user_core::forgot_password(state, payload, auth_id.clone()), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -431,21 +439,31 @@ pub async fn reset_password( .await } } + pub async fn invite_multiple_user( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<Vec<user_api::InviteUserRequest>>, - query: web::Query<user_api::TokenOnlyQueryParam>, + token_only_query_param: web::Query<user_api::TokenOnlyQueryParam>, + auth_id_query_param: web::Query<user_api::AuthIdQueryParam>, ) -> HttpResponse { let flow = Flow::InviteMultipleUser; - let is_token_only = query.into_inner().token_only; + let is_token_only = token_only_query_param.into_inner().token_only; + let auth_id = auth_id_query_param.into_inner().auth_id; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), |state, user, payload, req_state| { - user_core::invite_multiple_user(state, user, payload, req_state, is_token_only) + user_core::invite_multiple_user( + state, + user, + payload, + req_state, + is_token_only, + auth_id.clone(), + ) }, &auth::JWTAuth(Permission::UsersWrite), api_locking::LockAction::NotApplicable, @@ -458,14 +476,18 @@ pub async fn resend_invite( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::ReInviteUserRequest>, + query: web::Query<user_api::AuthIdQueryParam>, ) -> HttpResponse { let flow = Flow::ReInviteUser; + let auth_id = query.into_inner().auth_id; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), - user_core::resend_invite, + |state, user, req_payload, _| { + user_core::resend_invite(state, user, req_payload, auth_id.clone()) + }, &auth::JWTAuth(Permission::UsersWrite), api_locking::LockAction::NotApplicable, )) @@ -551,14 +573,16 @@ pub async fn verify_email_request( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SendVerifyEmailRequest>, + query: web::Query<user_api::AuthIdQueryParam>, ) -> HttpResponse { let flow = Flow::VerifyEmailRequest; + let auth_id = query.into_inner().auth_id; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), - |state, _, req_body, _| user_core::send_verification_mail(state, req_body), + |state, _, req_body, _| user_core::send_verification_mail(state, req_body, auth_id.clone()), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 878cd87ea23..1d4e77ff68a 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -190,14 +190,21 @@ pub fn get_link_with_token( base_url: impl std::fmt::Display, token: impl std::fmt::Display, action: impl std::fmt::Display, + auth_id: &Option<impl std::fmt::Display>, ) -> String { - format!("{base_url}/user/{action}?token={token}") + let email_url = format!("{base_url}/user/{action}?token={token}"); + if let Some(auth_id) = auth_id { + format!("{email_url}&auth_id={auth_id}") + } else { + email_url + } } pub struct VerifyEmail { pub recipient_email: domain::UserEmail, pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, + pub auth_id: Option<String>, } /// Currently only HTML is supported @@ -213,8 +220,12 @@ impl EmailData for VerifyEmail { .await .change_context(EmailError::TokenGenerationFailure)?; - let verify_email_link = - get_link_with_token(&self.settings.email.base_url, token, "verify_email"); + let verify_email_link = get_link_with_token( + &self.settings.user.base_url, + token, + "verify_email", + &self.auth_id, + ); let body = html::get_html_body(EmailBody::Verify { link: verify_email_link, @@ -233,6 +244,7 @@ pub struct ResetPassword { pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, + pub auth_id: Option<String>, } #[async_trait::async_trait] @@ -247,8 +259,12 @@ impl EmailData for ResetPassword { .await .change_context(EmailError::TokenGenerationFailure)?; - let reset_password_link = - get_link_with_token(&self.settings.email.base_url, token, "set_password"); + let reset_password_link = get_link_with_token( + &self.settings.user.base_url, + token, + "set_password", + &self.auth_id, + ); let body = html::get_html_body(EmailBody::Reset { link: reset_password_link, @@ -268,6 +284,7 @@ pub struct MagicLink { pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, + pub auth_id: Option<String>, } #[async_trait::async_trait] @@ -282,8 +299,12 @@ impl EmailData for MagicLink { .await .change_context(EmailError::TokenGenerationFailure)?; - let magic_link_login = - get_link_with_token(&self.settings.email.base_url, token, "verify_email"); + let magic_link_login = get_link_with_token( + &self.settings.user.base_url, + token, + "verify_email", + &self.auth_id, + ); let body = html::get_html_body(EmailBody::MagicLink { link: magic_link_login, @@ -305,6 +326,7 @@ pub struct InviteUser { pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, pub merchant_id: String, + pub auth_id: Option<String>, } #[async_trait::async_trait] @@ -319,8 +341,12 @@ impl EmailData for InviteUser { .await .change_context(EmailError::TokenGenerationFailure)?; - let invite_user_link = - get_link_with_token(&self.settings.email.base_url, token, "set_password"); + let invite_user_link = get_link_with_token( + &self.settings.user.base_url, + token, + "set_password", + &self.auth_id, + ); let body = html::get_html_body(EmailBody::InviteUser { link: invite_user_link, @@ -341,6 +367,7 @@ pub struct InviteRegisteredUser { pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, pub merchant_id: String, + pub auth_id: Option<String>, } #[async_trait::async_trait] @@ -356,9 +383,10 @@ impl EmailData for InviteRegisteredUser { .change_context(EmailError::TokenGenerationFailure)?; let invite_user_link = get_link_with_token( - &self.settings.email.base_url, + &self.settings.user.base_url, token, "accept_invite_from_email", + &self.auth_id, ); let body = html::get_html_body(EmailBody::AcceptInviteFromEmail { link: invite_user_link,
2024-06-25T14:33:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR will introduce `auth_id` field in email types and also email APIs. When an email is triggered from a API which gets `auth_id`, then that will be used to construct the email URL as well. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 #5119. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> All the following APIs will accept a query param called `auth_id`. 1. /user/connect_account 2. /user/forgot_password 3. /user/user/invite_multiple 4. /user/resend_invite 5. /user/verify_email_request Example: ``` curl --location 'http://localhost:8080/user/connect_account?auth_id=2d784c51-c6ba-4adf-8d9f-407049ddacd2' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email" }' ``` In the email received from the API, the url in the email will also have the same `auth_id` query param which is the same value as above. `auth_id` param is optional, and if it is not sent, the email link also will not have any parameter. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ffe90a41125a0eb1e8a858b336120e355fd3b69e
juspay/hyperswitch
juspay__hyperswitch-5096
Bug: feat(globalsearch): Implement tag-based filters in global search Add more explicit filters to global search: Currently we rely on free form text search where opensearch matches the keywords across the entire document We want to add a more refined & strict search query where we do exact matches on fields filters to be added: - payment method - currency - status - customer_email will need to add a filter_in_range function for the query builder as well to generate the corresponding query
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index b8c582df1bf..05f89b655cf 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -371,7 +371,7 @@ pub struct OpenSearchQueryBuilder { pub query: String, pub offset: Option<i64>, pub count: Option<i64>, - pub filters: Vec<(String, String)>, + pub filters: Vec<(String, Vec<String>)>, } impl OpenSearchQueryBuilder { @@ -391,7 +391,7 @@ impl OpenSearchQueryBuilder { Ok(()) } - pub fn add_filter_clause(&mut self, lhs: String, rhs: String) -> QueryResult<()> { + pub fn add_filter_clause(&mut self, lhs: String, rhs: Vec<String>) -> QueryResult<()> { self.filters.push((lhs, rhs)); Ok(()) } @@ -403,7 +403,7 @@ impl OpenSearchQueryBuilder { let mut filters = self .filters .iter() - .map(|(k, v)| json!({"match_phrase" : {k : v}})) + .map(|(k, v)| json!({"terms" : {k : v}})) .collect::<Vec<Value>>(); query.append(&mut filters); diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index 373ca3acbb6..1237db061bd 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -20,9 +20,43 @@ pub async fn msearch_results( OpenSearchQueryBuilder::new(OpenSearchQuery::Msearch(indexes.clone()), req.query); query_builder - .add_filter_clause("merchant_id".to_string(), merchant_id.to_string()) + .add_filter_clause( + "merchant_id.keyword".to_string(), + vec![merchant_id.to_string()], + ) .switch()?; + if let Some(filters) = req.filters { + if let Some(currency) = filters.currency { + if !currency.is_empty() { + query_builder + .add_filter_clause("currency.keyword".to_string(), currency.clone()) + .switch()?; + } + }; + if let Some(status) = filters.status { + if !status.is_empty() { + query_builder + .add_filter_clause("status.keyword".to_string(), status.clone()) + .switch()?; + } + }; + if let Some(payment_method) = filters.payment_method { + if !payment_method.is_empty() { + query_builder + .add_filter_clause("payment_method.keyword".to_string(), payment_method.clone()) + .switch()?; + } + }; + if let Some(customer_email) = filters.customer_email { + if !customer_email.is_empty() { + query_builder + .add_filter_clause("customer_email.keyword".to_string(), customer_email.clone()) + .switch()?; + } + }; + }; + let response_text: OpenMsearchOutput = client .execute(query_builder) .await @@ -82,9 +116,42 @@ pub async fn search_results( OpenSearchQueryBuilder::new(OpenSearchQuery::Search(req.index), search_req.query); query_builder - .add_filter_clause("merchant_id".to_string(), merchant_id.to_string()) + .add_filter_clause( + "merchant_id.keyword".to_string(), + vec![merchant_id.to_string()], + ) .switch()?; + if let Some(filters) = search_req.filters { + if let Some(currency) = filters.currency { + if !currency.is_empty() { + query_builder + .add_filter_clause("currency.keyword".to_string(), currency.clone()) + .switch()?; + } + }; + if let Some(status) = filters.status { + if !status.is_empty() { + query_builder + .add_filter_clause("status.keyword".to_string(), status.clone()) + .switch()?; + } + }; + if let Some(payment_method) = filters.payment_method { + if !payment_method.is_empty() { + query_builder + .add_filter_clause("payment_method.keyword".to_string(), payment_method.clone()) + .switch()?; + } + }; + if let Some(customer_email) = filters.customer_email { + if !customer_email.is_empty() { + query_builder + .add_filter_clause("customer_email.keyword".to_string(), customer_email.clone()) + .switch()?; + } + }; + }; query_builder .set_offset_n_count(search_req.offset, search_req.count) .switch()?; diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index a01349d987f..b2af4f6759c 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -3,6 +3,9 @@ use serde_json::Value; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct SearchFilters { pub payment_method: Option<Vec<String>>, + pub currency: Option<Vec<String>>, + pub status: Option<Vec<String>>, + pub customer_email: Option<Vec<String>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
2024-06-27T20:28:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added more explicit filters to global search: Currently we rely on free form text search where opensearch matches the keywords across the entire document Filters added currently: - payment method - currency - status - customer_email Can map multiple options for every filter for global search ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 a more refined & strict search query where we do exact matches on fields provides better results ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested using local data by sending cURL requests through Postman. ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjQ1YWViMDgtOTBmNS00ZTM5LTljMjMtNDRkZmYxM2E4ODgwIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzE4MDE4MjIyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxOTk5MTA0MSwib3JnX2lkIjoib3JnXzFuR09tR2N2dUxPVnBXUDJYMUFIIn0.VWP2Lj3US2qPb0nIZtpR2cHyfDpYBsR9lc9PvfQNdXY' \ --header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '{ "query": "merchant_1718018222", "filters": { "currency": [ "INR", "USD" ] } }' ``` <img width="1240" alt="Screenshot 2024-06-28 at 1 48 53 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/5e99971b-7724-417e-bfe8-99cd96e38091"> <img width="1242" alt="Screenshot 2024-06-28 at 1 51 11 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/c4f4e0b5-979e-48a3-9c1b-bff5295bd62e"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2688d24d4963550ff3efee363194446a3c75cc59
juspay/hyperswitch
juspay__hyperswitch-5125
Bug: feat: create redirect and sso login api Required: - Api that should redirect to openidconnect provider login. - Api that should accept the `code` and `state` passed by `openidconnect` provider and continue with login flow.
diff --git a/Cargo.lock b/Cargo.lock index 8c7c88e6196..9b08fcbd57b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1430,6 +1430,12 @@ dependencies = [ "rustc-demangle", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base32" version = "0.4.0" @@ -2307,6 +2313,18 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.6" @@ -2328,6 +2346,34 @@ dependencies = [ "thiserror", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a677b8922c94e01bdbb12126b0bc852f00447528dee1782229af9c720c3f348" +dependencies = [ + "cfg-if 1.0.0", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "platforms", + "rustc_version 0.4.0", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.57", +] + [[package]] name = "darling" version = "0.14.4" @@ -2677,6 +2723,44 @@ version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + [[package]] name = "either" version = "1.10.0" @@ -2686,6 +2770,27 @@ dependencies = [ "serde", ] +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "encoding_rs" version = "0.8.33" @@ -2915,6 +3020,22 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "ff" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" +dependencies = [ + "rand_core", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "finl_unicode" version = "1.2.0" @@ -3197,6 +3318,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -3287,6 +3409,17 @@ dependencies = [ "tempfile", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + [[package]] name = "h2" version = "0.3.25" @@ -4550,6 +4683,26 @@ dependencies = [ "libc", ] +[[package]] +name = "oauth2" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c38841cdd844847e3e7c8d29cef9dcfed8877f8f56f9071f77843ecf3baf937f" +dependencies = [ + "base64 0.13.1", + "chrono", + "getrandom", + "http 0.2.12", + "rand", + "reqwest", + "serde", + "serde_json", + "serde_path_to_error", + "sha2", + "thiserror", + "url", +] + [[package]] name = "object" version = "0.32.2" @@ -4596,6 +4749,38 @@ dependencies = [ "utoipa", ] +[[package]] +name = "openidconnect" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f47e80a9cfae4462dd29c41e987edd228971d6565553fbc14b8a11e666d91590" +dependencies = [ + "base64 0.13.1", + "chrono", + "dyn-clone", + "ed25519-dalek", + "hmac", + "http 0.2.12", + "itertools 0.10.5", + "log", + "oauth2", + "p256", + "p384", + "rand", + "rsa", + "serde", + "serde-value", + "serde_derive", + "serde_json", + "serde_path_to_error", + "serde_plain", + "serde_with", + "sha2", + "subtle", + "thiserror", + "url", +] + [[package]] name = "opensearch" version = "2.2.0" @@ -4743,6 +4928,15 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + [[package]] name = "ordered-multimap" version = "0.6.0" @@ -4765,6 +4959,30 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70786f51bcc69f6a4c0360e063a4cac5419ef7c5cd5b3c99ad70f3be5ba79209" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + [[package]] name = "parking_lot" version = "0.9.0" @@ -5040,6 +5258,12 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" +[[package]] +name = "platforms" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db23d408679286588f4d4644f965003d056e3dd5abcaaa938116871d7ce2fee7" + [[package]] name = "plotters" version = "0.3.5" @@ -5123,6 +5347,15 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro-crate" version = "1.3.1" @@ -5584,6 +5817,16 @@ dependencies = [ "winreg", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + [[package]] name = "ring" version = "0.16.20" @@ -5728,6 +5971,7 @@ dependencies = [ "num_cpus", "once_cell", "openapi", + "openidconnect", "openssl", "pm_auth", "qrcode", @@ -6116,6 +6360,20 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "2.9.2" @@ -6172,6 +6430,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float", + "serde", +] + [[package]] name = "serde-wasm-bindgen" version = "0.5.0" diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index e5d217cd8ea..4f5651e0a3c 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -12,14 +12,14 @@ use crate::user::{ }, AcceptInviteFromEmailRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, CreateUserAuthenticationMethodRequest, - DashboardEntryResponse, ForgotPasswordRequest, GetUserAuthenticationMethodsRequest, - GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, - InviteUserRequest, ListUsersResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, - RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest, - SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, - TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, - UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, - VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + DashboardEntryResponse, ForgotPasswordRequest, GetSsoAuthUrlRequest, + GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, + GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest, + RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, + SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, + SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse, + UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, + UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -81,7 +81,9 @@ common_utils::impl_misc_api_event_type!( RecoveryCodes, GetUserAuthenticationMethodsRequest, CreateUserAuthenticationMethodRequest, - UpdateUserAuthenticationMethodRequest + UpdateUserAuthenticationMethodRequest, + GetSsoAuthUrlRequest, + SsoSignInRequest ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 0006afea0d9..b2ed491b677 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -306,8 +306,9 @@ pub struct OpenIdConnectPublicConfig { pub name: OpenIdProvider, } -#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, strum::Display)] #[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] pub enum OpenIdProvider { Okta, } @@ -356,6 +357,17 @@ pub struct AuthMethodDetails { pub name: Option<OpenIdProvider>, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct GetSsoAuthUrlRequest { + pub id: String, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct SsoSignInRequest { + pub state: Secret<String>, + pub code: Secret<String>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthIdQueryParam { pub auth_id: Option<String>, diff --git a/crates/diesel_models/src/query/user_authentication_method.rs b/crates/diesel_models/src/query/user_authentication_method.rs index 08ea6556b82..14a28269cec 100644 --- a/crates/diesel_models/src/query/user_authentication_method.rs +++ b/crates/diesel_models/src/query/user_authentication_method.rs @@ -12,6 +12,13 @@ impl UserAuthenticationMethodNew { } impl UserAuthenticationMethod { + pub async fn get_user_authentication_method_by_id( + conn: &PgPooledConn, + id: &str, + ) -> StorageResult<Self> { + generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await + } + pub async fn list_user_authentication_methods_for_auth_id( conn: &PgPooledConn, auth_id: &str, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e48a6b44194..dd14c8d8960 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -66,6 +66,7 @@ mime = "0.3.17" nanoid = "0.4.0" num_cpus = "1.16.0" once_cell = "1.19.0" +openidconnect = "3.5.0" # TODO: remove reqwest openssl = "0.10.64" qrcode = "0.14.0" rand = "0.8.5" diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index b471448368f..40c5c385007 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -126,7 +126,7 @@ pub mod routes { state, &req, domain.into_inner(), - |_, _, domain: analytics::AnalyticsDomain, _| async { + |_, _: (), domain: analytics::AnalyticsDomain, _| async { analytics::core::get_domain_info(domain) .await .map(ApplicationResponse::Json) diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 331c256e8a4..261f8a1efcc 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -19,3 +19,6 @@ pub const REDIS_TOTP_PREFIX: &str = "TOTP_"; pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_"; pub const REDIS_TOTP_SECRET_PREFIX: &str = "TOTP_SEC_"; pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 15 * 60; // 15 minutes + +pub const REDIS_SSO_PREFIX: &str = "SSO_"; +pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 28b80e16cc0..1cd37679ad4 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -86,6 +86,8 @@ pub enum UserErrors { InvalidUserAuthMethodOperation, #[error("Auth config parsing error")] AuthConfigParsingError, + #[error("Invalid SSO request")] + SSOFailed, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -219,6 +221,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::AuthConfigParsingError => { AER::BadRequest(ApiError::new(sub_code, 45, self.get_error_message(), None)) } + Self::SSOFailed => { + AER::BadRequest(ApiError::new(sub_code, 46, self.get_error_message(), None)) + } } } } @@ -265,6 +270,7 @@ impl UserErrors { Self::UserAuthMethodAlreadyExists => "User auth method already exists", Self::InvalidUserAuthMethodOperation => "Invalid user auth method operation", Self::AuthConfigParsingError => "Auth config parsing error", + Self::SSOFailed => "Invalid SSO request", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 0fd583143cc..c4260a92948 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,6 +1,9 @@ use std::collections::HashMap; -use api_models::user::{self as user_api, InviteMultipleUserResponse}; +use api_models::{ + payments::RedirectionResponse, + user::{self as user_api, InviteMultipleUserResponse}, +}; use common_utils::ext_traits::ValueExt; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; @@ -13,7 +16,7 @@ use diesel_models::{ use error_stack::{report, ResultExt}; #[cfg(feature = "email")] use external_services::email::EmailData; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "email")] use router_env::env; use router_env::logger; @@ -26,7 +29,7 @@ use crate::services::email::types as email_types; use crate::{ consts, routes::{app::ReqState, SessionState}, - services::{authentication as auth, authorization::roles, ApplicationResponse}, + services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse}, types::{domain, transformers::ForeignInto}, utils::{self, user::two_factor_auth as tfa_utils}, }; @@ -2198,3 +2201,114 @@ pub async fn list_user_authentication_methods( .collect::<UserResult<_>>()?, )) } + +pub async fn get_sso_auth_url( + state: SessionState, + request: user_api::GetSsoAuthUrlRequest, +) -> UserResponse<()> { + let user_authentication_method = state + .store + .get_user_authentication_method_by_id(request.id.as_str()) + .await + .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; + + let open_id_private_config = + utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) + .await?; + + let open_id_public_config: user_api::OpenIdConnectPublicConfig = user_authentication_method + .public_config + .ok_or(UserErrors::InternalServerError) + .attach_printable("Public config not present")? + .parse_value("OpenIdConnectPublicConfig") + .change_context(UserErrors::InternalServerError) + .attach_printable("unable to parse OpenIdConnectPublicConfig")?; + + let oidc_state = Secret::new(nanoid::nanoid!()); + utils::user::set_sso_id_in_redis(&state, oidc_state.clone(), request.id).await?; + + let redirect_url = + utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string()); + + openidconnect::get_authorization_url( + state, + redirect_url, + oidc_state, + open_id_private_config.base_url.into(), + open_id_private_config.client_id, + ) + .await + .map(|url| { + ApplicationResponse::JsonForRedirection(RedirectionResponse { + headers: Vec::with_capacity(0), + return_url: String::new(), + http_method: String::new(), + params: Vec::with_capacity(0), + return_url_with_query_params: url.to_string(), + }) + }) +} + +pub async fn sso_sign( + state: SessionState, + request: user_api::SsoSignInRequest, + user_from_single_purpose_token: Option<auth::UserFromSinglePurposeToken>, +) -> UserResponse<user_api::TokenResponse> { + let authentication_method_id = + utils::user::get_sso_id_from_redis(&state, request.state.clone()).await?; + + let user_authentication_method = state + .store + .get_user_authentication_method_by_id(&authentication_method_id) + .await + .change_context(UserErrors::InternalServerError)?; + + let open_id_private_config = + utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) + .await?; + + let open_id_public_config: user_api::OpenIdConnectPublicConfig = user_authentication_method + .public_config + .ok_or(UserErrors::InternalServerError) + .attach_printable("Public config not present")? + .parse_value("OpenIdConnectPublicConfig") + .change_context(UserErrors::InternalServerError) + .attach_printable("unable to parse OpenIdConnectPublicConfig")?; + + let redirect_url = + utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string()); + let email = openidconnect::get_user_email_from_oidc_provider( + &state, + redirect_url, + request.state, + open_id_private_config.base_url.into(), + open_id_private_config.client_id, + request.code, + open_id_private_config.client_secret, + ) + .await?; + + // TODO: Use config to handle not found error + let user_from_db = state + .global_store + .find_user_by_email(&email.into_inner()) + .await + .map(Into::into) + .to_not_found_response(UserErrors::UserNotFound)?; + + let next_flow = if let Some(user_from_single_purpose_token) = user_from_single_purpose_token { + let current_flow = + domain::CurrentFlow::new(user_from_single_purpose_token, domain::SPTFlow::SSO.into())?; + current_flow.next(user_from_db, &state).await? + } else { + domain::NextFlow::from_origin(domain::Origin::SignInWithSSO, user_from_db, &state).await? + }; + + let token = next_flow.get_token(&state).await?; + let response = user_api::TokenResponse { + token: token.clone(), + token_type: next_flow.get_flow().into(), + }; + + auth::cookies::set_cookie_response(response, token) +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index e60bcc79bdb..e5686d616d4 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2971,6 +2971,15 @@ impl UserAuthenticationMethodInterface for KafkaStore { .await } + async fn get_user_authentication_method_by_id( + &self, + id: &str, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + self.diesel_store + .get_user_authentication_method_by_id(id) + .await + } + async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, diff --git a/crates/router/src/db/user_authentication_method.rs b/crates/router/src/db/user_authentication_method.rs index 5b9aa5da8c9..bcc2313d5db 100644 --- a/crates/router/src/db/user_authentication_method.rs +++ b/crates/router/src/db/user_authentication_method.rs @@ -16,6 +16,11 @@ pub trait UserAuthenticationMethodInterface { user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; + async fn get_user_authentication_method_by_id( + &self, + id: &str, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; + async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, @@ -47,6 +52,17 @@ impl UserAuthenticationMethodInterface for Store { .map_err(|error| report!(errors::StorageError::from(error))) } + #[instrument(skip_all)] + async fn get_user_authentication_method_by_id( + &self, + id: &str, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::UserAuthenticationMethod::get_user_authentication_method_by_id(&conn, id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + #[instrument(skip_all)] async fn list_user_authentication_methods_for_auth_id( &self, @@ -120,6 +136,28 @@ impl UserAuthenticationMethodInterface for MockDb { Ok(user_authentication_method) } + #[instrument(skip_all)] + async fn get_user_authentication_method_by_id( + &self, + id: &str, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + let user_authentication_methods = self.user_authentication_methods.lock().await; + + let user_authentication_method = user_authentication_methods + .iter() + .find(|&auth_method_inner| auth_method_inner.id == id); + + if let Some(user_authentication_method) = user_authentication_method { + Ok(user_authentication_method.to_owned()) + } else { + return Err(errors::StorageError::ValueNotFound(format!( + "No user authentication method found for id = {}", + id + )) + .into()); + } + } + async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index b91129f4575..3ef906c6ebc 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1347,6 +1347,8 @@ impl User { route = route .service(web::resource("").route(web::get().to(get_user_details))) .service(web::resource("/v2/signin").route(web::post().to(user_signin))) + // signin/signup with sso using openidconnect + .service(web::resource("/oidc").route(web::post().to(sso_sign))) .service(web::resource("/signout").route(web::post().to(signout))) .service(web::resource("/rotate_password").route(web::post().to(rotate_password))) .service(web::resource("/change_password").route(web::post().to(change_password))) @@ -1410,7 +1412,8 @@ impl User { ) .service( web::resource("/list").route(web::get().to(list_user_authentication_methods)), - ), + ) + .service(web::resource("/url").route(web::get().to(get_sso_auth_url))), ); #[cfg(feature = "email")] diff --git a/crates/router/src/routes/dummy_connector.rs b/crates/router/src/routes/dummy_connector.rs index 79338fc620c..a0c85f90ef7 100644 --- a/crates/router/src/routes/dummy_connector.rs +++ b/crates/router/src/routes/dummy_connector.rs @@ -27,7 +27,7 @@ pub async fn dummy_connector_authorize_payment( state, &req, payload, - |state, _, req, _| core::payment_authorize(state, req), + |state, _: (), req, _| core::payment_authorize(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -51,7 +51,7 @@ pub async fn dummy_connector_complete_payment( state, &req, payload, - |state, _, req, _| core::payment_complete(state, req), + |state, _: (), req, _| core::payment_complete(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -70,7 +70,7 @@ pub async fn dummy_connector_payment( state, &req, payload, - |state, _, req, _| core::payment(state, req), + |state, _: (), req, _| core::payment(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -90,7 +90,7 @@ pub async fn dummy_connector_payment_data( state, &req, payload, - |state, _, req, _| core::payment_data(state, req), + |state, _: (), req, _| core::payment_data(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -111,7 +111,7 @@ pub async fn dummy_connector_refund( state, &req, payload, - |state, _, req, _| core::refund_payment(state, req), + |state, _: (), req, _| core::refund_payment(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -131,7 +131,7 @@ pub async fn dummy_connector_refund_data( state, &req, payload, - |state, _, req, _| core::refund_data(state, req), + |state, _: (), req, _| core::refund_data(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index 3e2f42bcc25..f15a0db1923 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -34,7 +34,7 @@ pub async fn deep_health_check( state, &request, (), - |state, _, _, _| deep_health_check_func(state), + |state, _: (), _, _| deep_health_check_func(state), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index b18720652cf..28698146410 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -229,7 +229,9 @@ impl From<Flow> for ApiIdentifier { | Flow::TwoFactorAuthStatus | Flow::CreateUserAuthenticationMethod | Flow::UpdateUserAuthenticationMethod - | Flow::ListUserAuthenticationMethods => Self::User, + | Flow::ListUserAuthenticationMethods + | Flow::GetSsoAuthUrl + | Flow::SignInWithSso => Self::User, Flow::ListRoles | Flow::GetRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 816e7f7e2f8..dae78d31bf0 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -72,7 +72,7 @@ pub async fn user_signup( state, &http_req, req_payload.clone(), - |state, _, req_body, _| async move { + |state, _: (), req_body, _| async move { if let Some(true) = is_token_only { user_core::signup_token_only_flow(state, req_body).await } else { @@ -99,7 +99,7 @@ pub async fn user_signin( state, &http_req, req_payload.clone(), - |state, _, req_body, _| async move { + |state, _: (), req_body, _| async move { if let Some(true) = is_token_only { user_core::signin_token_only_flow(state, req_body).await } else { @@ -127,7 +127,7 @@ pub async fn user_connect_account( state, &http_req, req_payload.clone(), - |state, _, req_body, _| user_core::connect_account(state, req_body, auth_id.clone()), + |state, _: (), req_body, _| user_core::connect_account(state, req_body, auth_id.clone()), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -397,7 +397,7 @@ pub async fn forgot_password( state.clone(), &req, payload.into_inner(), - |state, _, payload, _| user_core::forgot_password(state, payload, auth_id.clone()), + |state, _: (), payload, _| user_core::forgot_password(state, payload, auth_id.clone()), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -432,7 +432,7 @@ pub async fn reset_password( state.clone(), &req, payload.into_inner(), - |state, _, payload, _| user_core::reset_password(state, payload), + |state, _: (), payload, _| user_core::reset_password(state, payload), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -522,7 +522,7 @@ pub async fn accept_invite_from_email( state.clone(), &req, payload.into_inner(), - |state, _, request_payload, _| { + |state, _: (), request_payload, _| { user_core::accept_invite_from_email(state, request_payload) }, &auth::NoAuth, @@ -560,7 +560,7 @@ pub async fn verify_email( state, &http_req, json_payload.into_inner(), - |state, _, req_payload, _| user_core::verify_email(state, req_payload), + |state, _: (), req_payload, _| user_core::verify_email(state, req_payload), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -582,7 +582,9 @@ pub async fn verify_email_request( state.clone(), &http_req, json_payload.into_inner(), - |state, _, req_body, _| user_core::send_verification_mail(state, req_body, auth_id.clone()), + |state, _: (), req_body, _| { + user_core::send_verification_mail(state, req_body, auth_id.clone()) + }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -774,6 +776,50 @@ pub async fn check_two_factor_auth_status( .await } +pub async fn get_sso_auth_url( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<user_api::GetSsoAuthUrlRequest>, +) -> HttpResponse { + let flow = Flow::GetSsoAuthUrl; + let payload = query.into_inner(); + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload, + |state, _: (), req, _| user_core::get_sso_auth_url(state, req), + &auth::NoAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn sso_sign( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::SsoSignInRequest>, +) -> HttpResponse { + let flow = Flow::SignInWithSso; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload, + |state, user: Option<auth::UserFromSinglePurposeToken>, payload, _| { + user_core::sso_sign(state, payload, user) + }, + auth::auth_type( + &auth::NoAuth, + &auth::SinglePurposeJWTAuth(TokenPurpose::SSO), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn create_user_authentication_method( state: web::Data<AppState>, req: HttpRequest, @@ -824,7 +870,7 @@ pub async fn list_user_authentication_methods( state.clone(), &req, query.into_inner(), - |state, _, req, _| user_core::list_user_authentication_methods(state, req), + |state, _: (), req, _| user_core::list_user_authentication_methods(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 7aed9fdb40a..8792f0c8d80 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -14,6 +14,9 @@ pub mod pm_auth; #[cfg(feature = "recon")] pub mod recon; +#[cfg(feature = "olap")] +pub mod openidconnect; + use std::sync::Arc; use error_stack::ResultExt; diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index add93e99119..7f8a01736ed 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -80,7 +80,7 @@ fn get_base_client( // We may need to use outbound proxy to connect to external world. // Precedence will be the environment variables, followed by the config. -pub(super) fn create_client( +pub fn create_client( proxy_config: &Proxy, should_bypass_proxy: bool, client_certificate: Option<masking::Secret<String>>, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 43d49b92efb..adca724e454 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -261,6 +261,20 @@ where } } +#[async_trait] +impl<A, T> AuthenticateAndFetch<Option<T>, A> for NoAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + _request_headers: &HeaderMap, + _state: &A, + ) -> RouterResult<(Option<T>, AuthenticationType)> { + Ok((None, AuthenticationType::NoAuth)) + } +} + #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth where @@ -372,6 +386,40 @@ where } } +#[cfg(feature = "olap")] +#[async_trait] +impl<A> AuthenticateAndFetch<Option<UserFromSinglePurposeToken>, A> for SinglePurposeJWTAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(Option<UserFromSinglePurposeToken>, AuthenticationType)> { + let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?; + if payload.check_in_blacklist(state).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + + if self.0 != payload.purpose { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + + Ok(( + Some(UserFromSinglePurposeToken { + user_id: payload.user_id.clone(), + origin: payload.origin.clone(), + path: payload.path, + }), + AuthenticationType::SinglePurposeJwt { + user_id: payload.user_id, + purpose: payload.purpose, + }, + )) + } +} + #[cfg(feature = "olap")] #[derive(Debug)] pub struct SinglePurposeOrLoginTokenAuth(pub TokenPurpose); diff --git a/crates/router/src/services/openidconnect.rs b/crates/router/src/services/openidconnect.rs new file mode 100644 index 00000000000..4f5056f3273 --- /dev/null +++ b/crates/router/src/services/openidconnect.rs @@ -0,0 +1,197 @@ +use error_stack::ResultExt; +use masking::{ExposeInterface, Secret}; +use oidc::TokenResponse; +use openidconnect::{self as oidc, core as oidc_core}; +use redis_interface::RedisConnectionPool; +use storage_impl::errors::ApiClientError; + +use crate::{ + consts, + core::errors::{UserErrors, UserResult}, + routes::SessionState, + services::api::client, + types::domain::user::UserEmail, +}; + +pub async fn get_authorization_url( + state: SessionState, + redirect_url: String, + redirect_state: Secret<String>, + base_url: Secret<String>, + client_id: Secret<String>, +) -> UserResult<url::Url> { + let discovery_document = get_discovery_document(base_url, &state).await?; + + let (auth_url, csrf_token, nonce) = + get_oidc_core_client(discovery_document, client_id, None, redirect_url)? + .authorize_url( + oidc_core::CoreAuthenticationFlow::AuthorizationCode, + || oidc::CsrfToken::new(redirect_state.expose()), + oidc::Nonce::new_random, + ) + .add_scope(oidc::Scope::new("email".to_string())) + .url(); + + // Save csrf & nonce as key value respectively + let key = get_oidc_redis_key(csrf_token.secret()); + get_redis_connection(&state)? + .set_key_with_expiry(&key, nonce.secret(), consts::user::REDIS_SSO_TTL) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to save csrf-nonce in redis")?; + + Ok(auth_url) +} + +pub async fn get_user_email_from_oidc_provider( + state: &SessionState, + redirect_url: String, + redirect_state: Secret<String>, + base_url: Secret<String>, + client_id: Secret<String>, + authorization_code: Secret<String>, + client_secret: Secret<String>, +) -> UserResult<UserEmail> { + let nonce = get_nonce_from_redis(state, &redirect_state).await?; + let discovery_document = get_discovery_document(base_url, state).await?; + let client = get_oidc_core_client( + discovery_document, + client_id, + Some(client_secret), + redirect_url, + )?; + + let nonce_clone = nonce.clone(); + client + .authorize_url( + oidc_core::CoreAuthenticationFlow::AuthorizationCode, + || oidc::CsrfToken::new(redirect_state.expose()), + || nonce_clone, + ) + .add_scope(oidc::Scope::new("email".to_string())); + + // Send request to OpenId provider with authorization code + let token_response = client + .exchange_code(oidc::AuthorizationCode::new(authorization_code.expose())) + .request_async(|req| get_oidc_reqwest_client(state, req)) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to exchange code and fetch oidc token")?; + + // Fetch id token from response + let id_token = token_response + .id_token() + .ok_or(UserErrors::InternalServerError) + .attach_printable("Id Token not provided in token response")?; + + // Verify id token + let id_token_claims = id_token + .claims(&client.id_token_verifier(), &nonce) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to verify id token")?; + + // Get email from token + let email_from_token = id_token_claims + .email() + .map(|email| email.to_string()) + .ok_or(UserErrors::InternalServerError) + .attach_printable("OpenID Provider Didnt provide email")?; + + UserEmail::new(Secret::new(email_from_token)) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to create email type") +} + +// TODO: Cache Discovery Document +async fn get_discovery_document( + base_url: Secret<String>, + state: &SessionState, +) -> UserResult<oidc_core::CoreProviderMetadata> { + let issuer_url = + oidc::IssuerUrl::new(base_url.expose()).change_context(UserErrors::InternalServerError)?; + oidc_core::CoreProviderMetadata::discover_async(issuer_url, |req| { + get_oidc_reqwest_client(state, req) + }) + .await + .change_context(UserErrors::InternalServerError) +} + +fn get_oidc_core_client( + discovery_document: oidc_core::CoreProviderMetadata, + client_id: Secret<String>, + client_secret: Option<Secret<String>>, + redirect_url: String, +) -> UserResult<oidc_core::CoreClient> { + let client_id = oidc::ClientId::new(client_id.expose()); + let client_secret = client_secret.map(|secret| oidc::ClientSecret::new(secret.expose())); + let redirect_url = oidc::RedirectUrl::new(redirect_url) + .change_context(UserErrors::InternalServerError) + .attach_printable("Error creating redirect URL type")?; + + Ok( + oidc_core::CoreClient::from_provider_metadata(discovery_document, client_id, client_secret) + .set_redirect_uri(redirect_url), + ) +} + +async fn get_nonce_from_redis( + state: &SessionState, + redirect_state: &Secret<String>, +) -> UserResult<oidc::Nonce> { + let redis_connection = get_redis_connection(state)?; + let redirect_state = redirect_state.clone().expose(); + let key = get_oidc_redis_key(&redirect_state); + redis_connection + .get_key::<Option<String>>(&key) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error Fetching CSRF from redis")? + .map(oidc::Nonce::new) + .ok_or(UserErrors::SSOFailed) + .attach_printable("Cannot find csrf in redis. Csrf invalid or expired") +} + +async fn get_oidc_reqwest_client( + state: &SessionState, + request: oidc::HttpRequest, +) -> Result<oidc::HttpResponse, ApiClientError> { + let client = client::create_client(&state.conf.proxy, false, None, None) + .map_err(|e| e.current_context().to_owned())?; + + let mut request_builder = client + .request(request.method, request.url) + .body(request.body); + for (name, value) in &request.headers { + request_builder = request_builder.header(name.as_str(), value.as_bytes()); + } + + let request = request_builder + .build() + .map_err(|_| ApiClientError::ClientConstructionFailed)?; + let response = client + .execute(request) + .await + .map_err(|_| ApiClientError::RequestNotSent("OpenIDConnect".to_string()))?; + + Ok(oidc::HttpResponse { + status_code: response.status(), + headers: response.headers().to_owned(), + body: response + .bytes() + .await + .map_err(|_| ApiClientError::ResponseDecodingFailed)? + .to_vec(), + }) +} + +fn get_oidc_redis_key(csrf: &str) -> String { + format!("{}OIDC_{}", consts::user::REDIS_SSO_PREFIX, csrf) +} + +fn get_redis_connection(state: &SessionState) -> UserResult<std::sync::Arc<RedisConnectionPool>> { + state + .store + .get_redis_conn() + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get redis connection") +} diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 25c851549d1..6b957281f76 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -1,12 +1,14 @@ use std::{collections::HashMap, sync::Arc}; use api_models::user as user_api; -use common_utils::errors::CustomResult; -use diesel_models::{enums::UserStatus, user_role::UserRole}; +use common_utils::{errors::CustomResult, ext_traits::ValueExt}; +use diesel_models::{encryption::Encryption, enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; +use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; use crate::{ + consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, core::errors::{StorageError, UserErrors, UserResult}, routes::SessionState, services::{ @@ -78,7 +80,7 @@ pub async fn generate_jwt_auth_token( state: &SessionState, user: &UserFromStorage, user_role: &UserRole, -) -> UserResult<masking::Secret<String>> { +) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user.get_user_id().to_string(), user_role.merchant_id.clone(), @@ -87,7 +89,7 @@ pub async fn generate_jwt_auth_token( user_role.org_id.clone(), ) .await?; - Ok(masking::Secret::new(token)) + Ok(Secret::new(token)) } pub async fn generate_jwt_auth_token_with_custom_role_attributes( @@ -96,7 +98,7 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes( merchant_id: String, org_id: String, role_id: String, -) -> UserResult<masking::Secret<String>> { +) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user.get_user_id().to_string(), merchant_id, @@ -105,14 +107,14 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes( org_id, ) .await?; - Ok(masking::Secret::new(token)) + Ok(Secret::new(token)) } pub fn get_dashboard_entry_response( state: &SessionState, user: UserFromStorage, user_role: UserRole, - token: masking::Secret<String>, + token: Secret<String>, ) -> UserResult<user_api::DashboardEntryResponse> { let verification_days_left = get_verification_days_left(state, &user)?; @@ -189,7 +191,7 @@ pub async fn get_user_from_db_by_email( .map(UserFromStorage::from) } -pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> masking::Secret<String> { +pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> Secret<String> { match resp { user_api::SignInResponse::DashboardEntry(data) => data.token.clone(), user_api::SignInResponse::MerchantSelect(data) => data.token.clone(), @@ -213,3 +215,74 @@ impl ForeignFrom<user_api::AuthConfig> for common_enums::UserAuthType { } } } + +pub async fn decrypt_oidc_private_config( + state: &SessionState, + encrypted_config: Option<Encryption>, +) -> UserResult<user_api::OpenIdConnectPrivateConfig> { + let user_auth_key = hex::decode( + state + .conf + .user_auth_methods + .get_inner() + .encryption_key + .clone() + .expose(), + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to decode DEK")?; + + let private_config = domain::types::decrypt::<serde_json::Value, masking::WithType>( + encrypted_config, + &user_auth_key, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to decrypt private config")? + .ok_or(UserErrors::InternalServerError) + .attach_printable("Private config not found")? + .into_inner() + .expose(); + + private_config + .parse_value("OpenIdConnectPrivateConfig") + .change_context(UserErrors::InternalServerError) + .attach_printable("unable to parse OpenIdConnectPrivateConfig") +} + +pub async fn set_sso_id_in_redis( + state: &SessionState, + oidc_state: Secret<String>, + sso_id: String, +) -> UserResult<()> { + let connection = get_redis_connection(state)?; + let key = get_oidc_key(&oidc_state.expose()); + connection + .set_key_with_expiry(&key, sso_id, REDIS_SSO_TTL) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to set sso id in redis") +} + +pub async fn get_sso_id_from_redis( + state: &SessionState, + oidc_state: Secret<String>, +) -> UserResult<String> { + let connection = get_redis_connection(state)?; + let key = get_oidc_key(&oidc_state.expose()); + connection + .get_key::<Option<String>>(&key) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get sso id from redis")? + .ok_or(UserErrors::SSOFailed) + .attach_printable("Cannot find oidc state in redis. Oidc state invalid or expired") +} + +fn get_oidc_key(oidc_state: &str) -> String { + format!("{}{oidc_state}", REDIS_SSO_PREFIX) +} + +pub fn get_oidc_sso_redirect_url(state: &SessionState, provider: &str) -> String { + format!("{}/redirect/oidc/{}", state.conf.user.base_url, provider) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 0d146a9eb2b..af6f9be0482 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -432,6 +432,10 @@ pub enum Flow { UpdateUserAuthenticationMethod, // List user authentication methods ListUserAuthenticationMethods, + /// Get sso auth url + GetSsoAuthUrl, + /// Signin with SSO + SignInWithSso, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event
2024-06-26T10:33:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Two new apis give - generate and redirect to openid provider. - signin using data given by openid provider. <!-- Describe your changes in detail --> ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Required for users to signin using sso. <!-- 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). --> ## How did you test it? Redirect to sso ```sh curl --location '<BASE URL>/user/auth/url?id=<>' ``` Signin with sso. ```sh curl --location --request POST '<BASE URL>/user/oidc' \ --header 'Content-Type: application/json' \ --data-raw '{ "state":"", "code": "" }' ``` <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt --all` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
4ccd25d0dc0703f9ac9ff441bedc8a9ce4ce78c6
juspay/hyperswitch
juspay__hyperswitch-5113
Bug: Mark retry payment as failure if `connector_tokenization` fails When a payment confirm call is made the status of the payment would be `requires_payment_method` while performing connector pre-processing steps. If a there is an error during this step then the status remains in `requires_payment_method`. If the pre-processing steps succeeds, the status is changed to `processing` just before the authorize flow. Now if the status will be further updated based on the connector response. Now if there is an failure response from the connector and if the the retry feature is enabled for that merchant we go to the retry flow. Now for the chosen connector we perform the pre-processing steps, here if something fails the payment status remains in `processing` as previous during the first attempt the status was updated to `processing` during the authorize flow. In this case if something fails in the pre-processing steps during the retry we need to fail the payment.
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 10d091a3b84..53850e97afc 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -33,7 +33,6 @@ use crate::{ storage::enums, transformers::{ForeignFrom, ForeignTryFrom}, }, - unimplemented_payment_method, utils::OptionExt, }; @@ -1761,9 +1760,11 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent let payment_method_token = match payment_method_token { types::PaymentMethodToken::Token(payment_method_token) => payment_method_token, - types::PaymentMethodToken::ApplePayDecrypt(_) => Err( - unimplemented_payment_method!("Apple Pay", "Simplified", "Stripe"), - )?, + types::PaymentMethodToken::ApplePayDecrypt(_) => { + Err(errors::ConnectorError::InvalidWalletToken { + wallet_name: "Apple Pay".to_string(), + })? + } }; Some(StripePaymentMethodData::Wallet( StripeWallet::ApplepayPayment(ApplepayPayment { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 8290177f21b..69c55b152ed 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -302,6 +302,7 @@ where #[cfg(not(feature = "frm"))] None, &business_profile, + false, ) .await?; @@ -373,6 +374,7 @@ where #[cfg(not(feature = "frm"))] None, &business_profile, + false, ) .await?; @@ -1394,6 +1396,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest>( header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &storage::business_profile::BusinessProfile, + is_retry_payment: bool, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -1476,7 +1479,7 @@ where router_data = router_data.add_session_token(state, &connector).await?; - let mut should_continue_further = access_token::update_router_data_with_access_token_result( + let should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, @@ -1526,16 +1529,22 @@ where _ => (), }; - let pm_token = router_data - .add_payment_method_token(state, &connector, &tokenization_action) + let payment_method_token_response = router_data + .add_payment_method_token( + state, + &connector, + &tokenization_action, + should_continue_further, + ) .await?; - if let Some(payment_method_token) = pm_token.clone() { - router_data.payment_method_token = Some( - hyperswitch_domain_models::router_data::PaymentMethodToken::Token(Secret::new( - payment_method_token, - )), + + let mut should_continue_further = + tokenization::update_router_data_with_payment_method_token_result( + payment_method_token_response, + &mut router_data, + is_retry_payment, + should_continue_further, ); - }; (router_data, should_continue_further) = complete_preprocessing_steps_if_required( state, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 9ecd0c4c8a0..23ab253ee53 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -84,13 +84,17 @@ pub trait Feature<F, T> { _state: &SessionState, _connector: &api::ConnectorData, _tokenization_action: &payments::TokenizationAction, - ) -> RouterResult<Option<String>> + _should_continue_payment: bool, + ) -> RouterResult<types::PaymentMethodTokenResult> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { - Ok(None) + Ok(types::PaymentMethodTokenResult { + payment_method_token_result: Ok(None), + is_payment_method_tokenization_performed: false, + }) } async fn preprocessing_steps<'a>( diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 23971f3696c..c06d9a70e16 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -140,7 +140,8 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, - ) -> RouterResult<Option<String>> { + should_continue_payment: bool, + ) -> RouterResult<types::PaymentMethodTokenResult> { let request = self.request.clone(); tokenization::add_payment_method_token( state, @@ -148,6 +149,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu tokenization_action, self, types::PaymentMethodTokenizationData::try_from(request)?, + should_continue_payment, ) .await } 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 bb56cb5a7c5..6bef7e95859 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -103,7 +103,8 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> state: &SessionState, connector: &api::ConnectorData, _tokenization_action: &payments::TokenizationAction, - ) -> RouterResult<Option<String>> { + should_continue_payment: bool, + ) -> RouterResult<types::PaymentMethodTokenResult> { // TODO: remove this and handle it in core if matches!(connector.connector_name, types::Connector::Payme) { let request = self.request.clone(); @@ -113,10 +114,14 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> &payments::TokenizationAction::TokenizeInConnector, self, types::PaymentMethodTokenizationData::try_from(request)?, + should_continue_payment, ) .await } else { - Ok(None) + Ok(types::PaymentMethodTokenResult { + payment_method_token_result: Ok(None), + is_payment_method_tokenization_performed: false, + }) } } 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 07803a0c0fb..773677f3e7c 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -107,7 +107,8 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, - ) -> RouterResult<Option<String>> { + should_continue_payment: bool, + ) -> RouterResult<types::PaymentMethodTokenResult> { let request = self.request.clone(); tokenization::add_payment_method_token( state, @@ -115,6 +116,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup tokenization_action, self, types::PaymentMethodTokenizationData::try_from(request)?, + should_continue_payment, ) .await } diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index e8ceeaa7ecf..ef8e0c01fed 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -321,6 +321,7 @@ where api::HeaderPayload::default(), frm_suggestion, business_profile, + true, ) .await } diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index d6ceeee65e7..da18fd7dd5a 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -784,62 +784,109 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( tokenization_action: &payments::TokenizationAction, router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>, pm_token_request_data: types::PaymentMethodTokenizationData, -) -> RouterResult<Option<String>> { - match tokenization_action { - payments::TokenizationAction::TokenizeInConnector - | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(_) => { - let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - - let pm_token_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = - Err(types::ErrorResponse::default()); - - let pm_token_router_data = - helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( - router_data.clone(), - pm_token_request_data, - pm_token_response_data, + should_continue_payment: bool, +) -> RouterResult<types::PaymentMethodTokenResult> { + if should_continue_payment { + match tokenization_action { + payments::TokenizationAction::TokenizeInConnector + | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(_) => { + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let pm_token_response_data: Result< + types::PaymentsResponseData, + types::ErrorResponse, + > = Err(types::ErrorResponse::default()); + + let pm_token_router_data = + helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( + router_data.clone(), + pm_token_request_data, + pm_token_response_data, + ); + + router_data + .request + .set_session_token(pm_token_router_data.session_token.clone()); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &pm_token_router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payment_failed_response()?; + + metrics::CONNECTOR_PAYMENT_METHOD_TOKENIZATION.add( + &metrics::CONTEXT, + 1, + &add_attributes([ + ("connector", connector.connector_name.to_string()), + ("payment_method", router_data.payment_method.to_string()), + ]), ); - router_data - .request - .set_session_token(pm_token_router_data.session_token.clone()); - - let resp = services::execute_connector_processing_step( - state, - connector_integration, - &pm_token_router_data, - payments::CallConnectorAction::Trigger, - None, - ) - .await - .to_payment_failed_response()?; - - metrics::CONNECTOR_PAYMENT_METHOD_TOKENIZATION.add( - &metrics::CONTEXT, - 1, - &add_attributes([ - ("connector", connector.connector_name.to_string()), - ("payment_method", router_data.payment_method.to_string()), - ]), - ); - - let pm_token = match resp.response { - Ok(response) => match response { - types::PaymentsResponseData::TokenizationResponse { token } => Some(token), - _ => None, - }, - Err(err) => { + let payment_token_resp = resp.response.map(|res| { + if let types::PaymentsResponseData::TokenizationResponse { token } = res { + Some(token) + } else { + None + } + }); + + Ok(types::PaymentMethodTokenResult { + payment_method_token_result: payment_token_resp, + is_payment_method_tokenization_performed: true, + }) + } + _ => Ok(types::PaymentMethodTokenResult { + payment_method_token_result: Ok(None), + is_payment_method_tokenization_performed: false, + }), + } + } else { + logger::debug!("Skipping connector tokenization based on should_continue_payment flag"); + Ok(types::PaymentMethodTokenResult { + payment_method_token_result: Ok(None), + is_payment_method_tokenization_performed: false, + }) + } +} + +pub fn update_router_data_with_payment_method_token_result<F: Clone, T>( + payment_method_token_result: types::PaymentMethodTokenResult, + router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>, + is_retry_payment: bool, + should_continue_further: bool, +) -> bool { + if payment_method_token_result.is_payment_method_tokenization_performed { + match payment_method_token_result.payment_method_token_result { + Ok(pm_token_result) => { + router_data.payment_method_token = pm_token_result.map(|pm_token| { + hyperswitch_domain_models::router_data::PaymentMethodToken::Token( + masking::Secret::new(pm_token), + ) + }); + + true + } + Err(err) => { + if is_retry_payment { + router_data.response = Err(err); + false + } else { logger::debug!(payment_method_tokenization_error=?err); - None + true } - }; - Ok(pm_token) + } } - _ => Ok(None), + } else { + should_continue_further } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 607e5bd8234..f0087ef2f39 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -545,6 +545,11 @@ pub struct AddAccessTokenResult { pub connector_supports_access_token: bool, } +pub struct PaymentMethodTokenResult { + pub payment_method_token_result: Result<Option<String>, ErrorResponse>, + pub is_payment_method_tokenization_performed: bool, +} + #[derive(Debug, Clone, Copy)] pub enum Redirection { Redirect,
2024-06-25T07:13:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> When a payment confirm call is made the status of the payment would be `requires_payment_method` while performing connector pre-processing steps. If a there is an error during this step then the status remains in `requires_payment_method`. If the pre-processing steps succeeds, the status is changed to `processing` just before the authorize flow. Now if the status will be further updated based on the connector response. Now if there is an failure response from the connector and if the the retry feature is enabled for that merchant we go to the retry flow. Now for the chosen connector we perform the pre-processing steps, here if something fails the payment status remains in `processing` as previous during the first attempt the status was updated to `processing` during the authorize flow. In this case if something fails in the pre-processing steps during the retry we need to fail the payment. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create MCA of stripe with apple pay simplified flow enabled -> The connector api in the connector tokenizatoin flow is hardcoded wrongly for test purpose. So in this case if apple pay simplified payment request is made, the error response changes to `Invalid wallet token` from `unimplemented flow`. And also in the db the `payment_intent` status will be as `requires_payment_method`. <img width="1058" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1fd17ca1-5d82-455a-b92a-3c96ea4ab41d"> <img width="1263" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/8289bd07-2d5a-4887-8874-49ce13001ba5"> -> Configure one more connector (`BOA`) with simplified flow. And configure the routing rule such that the payment first go through `BOA` and retry happens through `Stripe`. -> Enable retry for the merchant account. ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "should_call_gsm_merchant_1719384197", "value": "true" }' ``` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "max_auto_retries_enabled_merchant_1719384197", "value": "2" }' ``` ``` curl --location 'localhost:8080/gsm' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "connector": "bankofamerica", "flow": "Authorize", "sub_flow": "sub_flow", "code": "No error code", "message": "Authentication Failed", "status": "Failure", "decision": "retry", "step_up_possible": false }' ``` -> Now I have hardcoded the `BOA` api key wrongly so that payment fails and will be retried with `Stripe`. Also the connector api in the connector tokenizatoin flow is hardcoded wrongly in `Stripe` to test if the payment reaches a terminal state (`failed`) if that connector tokenization call fails for stripe. ``` { "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "test_fb", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "eyJkYXRhIjoiVnJnTm9mYXRRZEFIME1MTjZjd1VMazdIS09PdWIvUnMwbEtFOW1vWllvcFhSSXpGemM4VDJiMzlpWjdWSGVXK0YxZVFmY0V5OFJrWjMvcWRZQkVyaE4wK1BxL2pRZ2xpZFNUNlYzdXNwRHB6MlJGSWxYUWhiODJndmd5Y3hSb1R6MER4MDgwNzQ1MUJkN1RMUldyVWNlaVRvdEN4N041ZXFVcjM3UTJlZ2hTaExNOWtXVzAxSmIvT3FLM3RLTUhZaFZNRmE2alNaaHduMVU1NitpbXR5SDMvS1BpdlJlQ0ZxTUtFVmJiRFRyNmpzSDEyNWUwVmlOalBXYm1kVzZJZWU2RDR0cjk5VEhiSkhiWUJzaVdrMUROb29tS28zbHRVUjRkMTZwL09Cc2xTYUh6dnFTL2VrOGVCTDB4dTB3TkMyamx5OFpQUnVZNGRZL2gyS3U0VmprL1BpTWtJUnRNVGl3MTFZWExXUHFNamkvM1N1VDcxUEFnZllpQU4zZmxYK1Q5RmVZRE5yVmdSNWFyRGN3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFRpb25JZCI6ImMxMTFjYzA1YzBkZjFiMjZmYTI3MjcwZDcyMjhmM2EzNDQ1ZTJhMDNiYTMyYjQ5NjI3ODEzNTVkYjc2M2VjNjMifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` <img width="1120" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d67a32d6-915b-46ca-b257-4a622897f005"> <img width="1198" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3ddc4fce-fa8c-4e7c-b91e-840d938f9dbf"> <img width="1397" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/7608db87-7610-4355-8dbb-584d1953984e"> -> When made the same above request without the changes in this pr. <img width="830" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/574fff8f-875b-4416-8272-a026f42853a9"> <img width="1117" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/ce8a6a3f-61d7-4d53-823b-c3f863fcad2e"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
af2497b5012f048a4cf72b61712812bca534c17c
juspay/hyperswitch
juspay__hyperswitch-5088
Bug: updated `last_used_at` field for apple pay and google pay for CITs updated `last_used_at` field for apple pay and google pay for CITs Currently, the `last_used_at` field for Apple Pay and Google Pay is not updated when an Apple Pay CIT (Cardholder Initiated Transaction) is made after Apple Pay has been saved. This needs to be update whenever the payment are made.
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs index 7fb0cfa28af..2bb981d03e8 100644 --- a/crates/router/src/core/mandate/helpers.rs +++ b/crates/router/src/core/mandate/helpers.rs @@ -70,9 +70,11 @@ pub fn get_mandate_type( Ok(Some(api::MandateTransactionType::NewMandateTransaction)) } - (_, _, Some(enums::FutureUsage::OffSession), _, Some(_)) | (_, Some(_), _, _, _) => Ok( - Some(api::MandateTransactionType::RecurringMandateTransaction), - ), + (_, _, Some(enums::FutureUsage::OffSession), _, Some(_)) + | (_, Some(_), _, _, _) + | (_, _, Some(enums::FutureUsage::OffSession), _, _) => Ok(Some( + api::MandateTransactionType::RecurringMandateTransaction, + )), _ => Ok(None), } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 9802860ef95..e9df375ab6e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -533,6 +533,63 @@ pub async fn get_token_pm_type_mandate_details( mandate_generic_data.mandate_connector, mandate_generic_data.payment_method_info, ) + } else if request.payment_method_type + == Some(api_models::enums::PaymentMethodType::ApplePay) + || request.payment_method_type + == Some(api_models::enums::PaymentMethodType::GooglePay) + { + if let Some(customer_id) = &request.customer_id { + let customer_saved_pm_option = match state + .store + .find_payment_method_by_customer_id_merchant_id_list( + customer_id, + merchant_account.merchant_id.as_str(), + None, + ) + .await + { + Ok(customer_payment_methods) => Ok(customer_payment_methods + .iter() + .find(|payment_method| { + payment_method.payment_method_type + == request.payment_method_type + }) + .cloned()), + Err(error) => { + if error.current_context().is_db_not_found() { + Ok(None) + } else { + Err(error) + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable( + "failed to find payment methods for a customer", + ) + } + } + }?; + + ( + None, + request.payment_method, + request.payment_method_type, + None, + None, + None, + customer_saved_pm_option, + ) + } else { + ( + None, + request.payment_method, + request.payment_method_type, + None, + None, + None, + None, + ) + } } else { ( request.payment_token.to_owned(),
2024-06-23T15:02:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> updated `last_used_at` field for apple pay and google pay for CITs Currently, the `last_used_at` field for Apple Pay and Google Pay is not updated when an Apple Pay CIT (Cardholder Initiated Transaction) is made after Apple Pay has been saved. This needs to be update whenever the payment are made. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create mca for cybersource -> Save apple pay for a customer ``` { "amount": 800, "currency": "USD", "confirm": true, "amount_to_capture": 800, "customer_id": "testing_123456", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "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" } }, "connector_metadata": { "noon": { "order_category": "pay" } } } ``` <img width="1147" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/8c554520-4619-4185-8d6f-8af1244946f6"> -> Create a card for customer ``` { "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "testing_123456", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "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": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "payment_type": "setup_mandate", "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "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": "John", "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": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` <img width="1121" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0a6384ef-6fba-425e-9014-ad7f88db15c3"> -> Do list customer payment methods. (In this card will appear in the top as it is last used) ``` curl --location 'http://localhost:8080/customers/testing_123456/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_n5vdXydG4AnJkQvTnVgH6ydjRqaheitMaZoEfx9eztar5xLkj7DP1nxBQ9DbwCt9' ``` <img width="1112" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a556b36d-6078-499f-a90b-6270ae6f10a6"> -> Now make apple pay payment for the same customer ``` { "amount": 800, "currency": "USD", "confirm": true, "amount_to_capture": 800, "customer_id": "testing_123456", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3FCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "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" } }, "connector_metadata": { "noon": { "order_category": "pay" } } } ``` <img width="1145" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/7e1ba013-df7a-4830-8767-23f209fc5e4a"> -> Perform list customer. (Now the apple pay should appear in the first as it is the last used) ``` curl --location 'http://localhost:8080/customers/testing_123456/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_eCYAPfeD2CrjCUdrLoopzHC8kFLJpA7hxcUE4D1pfCqOa1VKxYQhUjCNXqVQlJyv' ``` <img width="1158" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/7755276b-3d9b-4fc5-8b6c-e602254686f2"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
a71fe033e7de75171d140506ff4d51a362c185f4
juspay/hyperswitch
juspay__hyperswitch-5095
Bug: fix(analytics): use HashSet to represent the returned metrics Currently we have 2 sources for analytics Clickhouse & Sqlx Along with this we have a combined mode which helps compare for any differences in these results However since currently we return a vector of results this causes an mismatch warning if the order is changed, instead we should use a HashSet to store & compare these values. https://github.com/juspay/hyperswitch/blob/d4dba55fedc37ba9d1d54d28456ca17851ab9881/crates/analytics/src/api_event/metrics.rs#L41-L50 we can also add a Counter metric to determine whenever these metrics are incorrect.
diff --git a/crates/analytics/src/active_payments/metrics.rs b/crates/analytics/src/active_payments/metrics.rs index e7b4ff3f5b6..5526f30fd6e 100644 --- a/crates/analytics/src/active_payments/metrics.rs +++ b/crates/analytics/src/active_payments/metrics.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ active_payments::{ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier}, Granularity, TimeRange, @@ -13,7 +15,7 @@ mod active_payments; use active_payments::ActivePayments; -#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct ActivePaymentsMetricRow { pub count: Option<i64>, } @@ -32,7 +34,7 @@ where time_range: &TimeRange, pool: &T, ) -> MetricsResult< - Vec<( + HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, @@ -56,7 +58,7 @@ where time_range: &TimeRange, pool: &T, ) -> MetricsResult< - Vec<( + HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, diff --git a/crates/analytics/src/active_payments/metrics/active_payments.rs b/crates/analytics/src/active_payments/metrics/active_payments.rs index 60209e39755..30621c98c7e 100644 --- a/crates/analytics/src/active_payments/metrics/active_payments.rs +++ b/crates/analytics/src/active_payments/metrics/active_payments.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ active_payments::ActivePaymentsMetricsBucketIdentifier, Granularity, TimeRange, }; @@ -31,7 +33,7 @@ where time_range: &TimeRange, pool: &T, ) -> MetricsResult< - Vec<( + HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, @@ -79,7 +81,7 @@ where .into_iter() .map(|i| Ok((ActivePaymentsMetricsBucketIdentifier::new(None), i))) .collect::<error_stack::Result< - Vec<( + HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, diff --git a/crates/analytics/src/api_event/metrics.rs b/crates/analytics/src/api_event/metrics.rs index 16f2d7a2f5a..1a08b56a595 100644 --- a/crates/analytics/src/api_event/metrics.rs +++ b/crates/analytics/src/api_event/metrics.rs @@ -14,13 +14,15 @@ use crate::{ mod api_count; pub mod latency; mod status_code_count; +use std::collections::HashSet; + use api_count::ApiCount; use latency::MaxLatency; use status_code_count::StatusCodeCount; use self::latency::LatencyAvg; -#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct ApiEventMetricRow { pub latency: Option<u64>, pub api_count: Option<u64>, @@ -46,7 +48,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>>; + ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>>; } #[async_trait::async_trait] @@ -67,7 +69,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { match self { Self::Latency => { MaxLatency diff --git a/crates/analytics/src/api_event/metrics/api_count.rs b/crates/analytics/src/api_event/metrics/api_count.rs index 7f5f291aa53..cb9d559292d 100644 --- a/crates/analytics/src/api_event/metrics/api_count.rs +++ b/crates/analytics/src/api_event/metrics/api_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier}, Granularity, TimeRange, @@ -33,7 +35,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents); query_builder @@ -98,7 +100,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, + HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/api_event/metrics/latency.rs b/crates/analytics/src/api_event/metrics/latency.rs index 379b39fbeb9..20fb6489451 100644 --- a/crates/analytics/src/api_event/metrics/latency.rs +++ b/crates/analytics/src/api_event/metrics/latency.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier}, Granularity, TimeRange, @@ -36,7 +38,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents); query_builder @@ -120,7 +122,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, + HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/api_event/metrics/status_code_count.rs b/crates/analytics/src/api_event/metrics/status_code_count.rs index 5c652fd8e0c..a5130169213 100644 --- a/crates/analytics/src/api_event/metrics/status_code_count.rs +++ b/crates/analytics/src/api_event/metrics/status_code_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier}, Granularity, TimeRange, @@ -33,7 +35,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents); query_builder @@ -95,7 +97,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, + HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index ae61aefb858..6690850a80e 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, @@ -27,7 +29,7 @@ use frictionless_flow_count::FrictionlessFlowCount; use frictionless_success_count::FrictionlessSuccessCount; use three_ds_sdk_count::ThreeDsSdkCount; -#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct AuthEventMetricRow { pub count: Option<i64>, pub time_bucket: Option<String>, @@ -47,7 +49,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>>; + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>>; } #[async_trait::async_trait] @@ -67,7 +69,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { match self { Self::ThreeDsSdkCount => { ThreeDsSdkCount diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 01110858804..80c80db92fe 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); @@ -94,7 +96,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 6f0580bb0b5..bfcfbaf3a6a 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); @@ -94,7 +96,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index f2d2ab153f0..b146c053d3d 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); @@ -86,7 +88,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 49fef8941f7..b2921bb3ece 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); @@ -96,7 +98,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index b7d55714b60..f6553f84f8c 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); @@ -86,7 +88,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index 7ae9d773675..42261f09b3e 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); @@ -98,7 +100,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 2f05a050ce7..4d7eed972f4 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); @@ -86,7 +88,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs b/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs index b08d48b550a..05173bcb9da 100644 --- a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs +++ b/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); @@ -94,7 +96,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs index 4963626d0fa..e397785528c 100644 --- a/crates/analytics/src/disputes/metrics.rs +++ b/crates/analytics/src/disputes/metrics.rs @@ -2,6 +2,8 @@ mod dispute_status_metric; mod total_amount_disputed; mod total_dispute_lost_amount; +use std::collections::HashSet; + use api_models::{ analytics::{ disputes::{ @@ -22,7 +24,7 @@ use crate::{ query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; -#[derive(Debug, Eq, PartialEq, serde::Deserialize)] +#[derive(Debug, Eq, PartialEq, serde::Deserialize, Hash)] pub struct DisputeMetricRow { pub dispute_stage: Option<DBEnumWrapper<storage_enums::DisputeStage>>, pub dispute_status: Option<DBEnumWrapper<storage_enums::DisputeStatus>>, @@ -55,7 +57,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>; + ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>; } #[async_trait::async_trait] @@ -76,7 +78,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { + ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { match self { Self::TotalAmountDisputed => { TotalAmountDisputed::default() diff --git a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs index 5b97021becc..005be320eb5 100644 --- a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs +++ b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier}, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> + ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> where T: AnalyticsDataSource + super::DisputeMetricAnalytics, { @@ -111,7 +113,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>, + HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs index cbba553aa85..cf299ebfa9d 100644 --- a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs +++ b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier}, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> + ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> where T: AnalyticsDataSource + super::DisputeMetricAnalytics, { @@ -110,7 +112,7 @@ where i, )) }) - .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } } diff --git a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs index c7be2ab1a98..ddf6338f01f 100644 --- a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs +++ b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier}, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> + ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> where T: AnalyticsDataSource + super::DisputeMetricAnalytics, { @@ -111,7 +113,7 @@ where i, )) }) - .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 943ac9a5311..d6812100c8a 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -31,7 +31,7 @@ pub use types::AnalyticsDomain; pub mod lambda_utils; pub mod utils; -use std::sync::Arc; +use std::{collections::HashSet, sync::Arc}; use api_models::analytics::{ active_payments::{ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier}, @@ -113,7 +113,7 @@ impl AnalyticsProvider { filters: &PaymentFilters, granularity: &Option<Granularity>, time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> types::MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { // Metrics to get the fetch time for each payment metric metrics::request::record_operation_time( async { @@ -327,7 +327,7 @@ impl AnalyticsProvider { filters: &PaymentIntentFilters, granularity: &Option<Granularity>, time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + ) -> types::MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { // Metrics to get the fetch time for each payment intent metric metrics::request::record_operation_time( @@ -432,7 +432,7 @@ impl AnalyticsProvider { filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { + ) -> types::MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { // Metrics to get the fetch time for each refund metric metrics::request::record_operation_time( async { @@ -532,7 +532,7 @@ impl AnalyticsProvider { filters: &DisputeFilters, granularity: &Option<Granularity>, time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { + ) -> types::MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { // Metrics to get the fetch time for each refund metric metrics::request::record_operation_time( async { @@ -632,7 +632,7 @@ impl AnalyticsProvider { filters: &SdkEventFilters, granularity: &Option<Granularity>, time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> types::MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { match self { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { @@ -670,7 +670,7 @@ impl AnalyticsProvider { publishable_key: &str, time_range: &TimeRange, ) -> types::MetricsResult< - Vec<( + HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, @@ -697,7 +697,7 @@ impl AnalyticsProvider { publishable_key: &str, granularity: &Option<Granularity>, time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + ) -> types::MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { match self { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { @@ -728,7 +728,7 @@ impl AnalyticsProvider { filters: &ApiEventFilters, granularity: &Option<Granularity>, time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + ) -> types::MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { match self { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(ckh_pool) diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index e3932baaf07..c7546a4ab0d 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -1,5 +1,5 @@ #![allow(dead_code)] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use api_models::analytics::{ payment_intents::{ @@ -34,7 +34,7 @@ pub enum TaskType { MetricTask( PaymentIntentMetrics, CustomResult< - Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, AnalyticsError, >, ), diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs index 3a0cbbc85db..a06d76ce8fe 100644 --- a/crates/analytics/src/payment_intents/metrics.rs +++ b/crates/analytics/src/payment_intents/metrics.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetrics, @@ -23,7 +25,7 @@ use smart_retried_amount::SmartRetriedAmount; use successful_smart_retries::SuccessfulSmartRetries; use total_smart_retries::TotalSmartRetries; -#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct PaymentIntentMetricRow { pub status: Option<DBEnumWrapper<storage_enums::IntentStatus>>, pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, @@ -50,7 +52,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>; + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>; } #[async_trait::async_trait] @@ -71,7 +73,8 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { match self { Self::SuccessfulSmartRetries => { SuccessfulSmartRetries diff --git a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs index 0f235375c4f..5db153c8a36 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, @@ -35,7 +37,8 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::PaymentIntent); @@ -113,7 +116,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs index 470a0e66867..3b78a355828 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::{ analytics::{ payment_intents::{ @@ -41,7 +43,8 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::PaymentIntent); @@ -123,7 +126,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs index 292062d1e10..ef0bb6672f1 100644 --- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::{ analytics::{ payment_intents::{ @@ -41,7 +43,8 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::PaymentIntent); @@ -122,7 +125,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs index d5a3d142baf..3ef8c02aca2 100644 --- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, @@ -38,7 +40,8 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::PaymentIntent); @@ -117,7 +120,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index 2508866626a..e943bf0ac6b 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -1,5 +1,5 @@ #![allow(dead_code)] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use api_models::analytics::{ payments::{ @@ -34,7 +34,7 @@ use crate::{ pub enum TaskType { MetricTask( PaymentMetrics, - CustomResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, AnalyticsError>, + CustomResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, AnalyticsError>, ), DistributionTask( PaymentDistributions, diff --git a/crates/analytics/src/payments/metrics.rs b/crates/analytics/src/payments/metrics.rs index 59a9ca88a84..1dd1481688f 100644 --- a/crates/analytics/src/payments/metrics.rs +++ b/crates/analytics/src/payments/metrics.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, @@ -27,7 +29,7 @@ use success_rate::PaymentSuccessRate; use self::retries_count::RetriesCount; -#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct PaymentMetricRow { pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub status: Option<DBEnumWrapper<storage_enums::AttemptStatus>>, @@ -60,7 +62,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>>; + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>>; } #[async_trait::async_trait] @@ -81,7 +83,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { match self { Self::PaymentSuccessRate => { PaymentSuccessRate diff --git a/crates/analytics/src/payments/metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/avg_ticket_size.rs index 38ab0a9540d..1a1fbe52987 100644 --- a/crates/analytics/src/payments/metrics/avg_ticket_size.rs +++ b/crates/analytics/src/payments/metrics/avg_ticket_size.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, @@ -34,7 +36,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); for dim in dimensions.iter() { @@ -130,7 +132,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payments/metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/connector_success_rate.rs index 2742327f4ab..c5da4b51a0b 100644 --- a/crates/analytics/src/payments/metrics/connector_success_rate.rs +++ b/crates/analytics/src/payments/metrics/connector_success_rate.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, @@ -36,7 +38,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); let mut dimensions = dimensions.to_vec(); @@ -124,7 +126,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payments/metrics/payment_count.rs b/crates/analytics/src/payments/metrics/payment_count.rs index 50ea1791b39..6fd12edea74 100644 --- a/crates/analytics/src/payments/metrics/payment_count.rs +++ b/crates/analytics/src/payments/metrics/payment_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, @@ -33,7 +35,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); for dim in dimensions.iter() { @@ -115,7 +117,7 @@ where i, )) }) - .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } } diff --git a/crates/analytics/src/payments/metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/payment_processed_amount.rs index 6ea5b15734f..772156a070d 100644 --- a/crates/analytics/src/payments/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payments/metrics/payment_processed_amount.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, @@ -34,7 +36,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); for dim in dimensions.iter() { @@ -124,7 +126,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payments/metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/payment_success_count.rs index 4350700618e..ce63424d1c8 100644 --- a/crates/analytics/src/payments/metrics/payment_success_count.rs +++ b/crates/analytics/src/payments/metrics/payment_success_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, @@ -34,7 +36,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); for dim in dimensions.iter() { @@ -123,7 +125,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payments/metrics/retries_count.rs b/crates/analytics/src/payments/metrics/retries_count.rs index 3c4580d37a7..33aa7d3b0b6 100644 --- a/crates/analytics/src/payments/metrics/retries_count.rs +++ b/crates/analytics/src/payments/metrics/retries_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::{ analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, @@ -39,7 +41,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::PaymentIntent); query_builder @@ -119,7 +121,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/payments/metrics/success_rate.rs b/crates/analytics/src/payments/metrics/success_rate.rs index a0c67c1d807..1f48deaad16 100644 --- a/crates/analytics/src/payments/metrics/success_rate.rs +++ b/crates/analytics/src/payments/metrics/success_rate.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, @@ -33,7 +35,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); let mut dimensions = dimensions.to_vec(); @@ -119,7 +121,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs index 10cd0354677..d8a59e54888 100644 --- a/crates/analytics/src/refunds/metrics.rs +++ b/crates/analytics/src/refunds/metrics.rs @@ -10,6 +10,8 @@ mod refund_count; mod refund_processed_amount; mod refund_success_count; mod refund_success_rate; +use std::collections::HashSet; + use refund_count::RefundCount; use refund_processed_amount::RefundProcessedAmount; use refund_success_count::RefundSuccessCount; @@ -19,7 +21,8 @@ use crate::{ query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; -#[derive(Debug, Eq, PartialEq, serde::Deserialize)] + +#[derive(Debug, Eq, PartialEq, serde::Deserialize, Hash)] pub struct RefundMetricRow { pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub refund_status: Option<DBEnumWrapper<storage_enums::RefundStatus>>, @@ -53,7 +56,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>>; + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>; } #[async_trait::async_trait] @@ -74,7 +77,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { match self { Self::RefundSuccessRate => { RefundSuccessRate::default() diff --git a/crates/analytics/src/refunds/metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/refund_count.rs index cf3c7a50927..14240ff8e13 100644 --- a/crates/analytics/src/refunds/metrics/refund_count.rs +++ b/crates/analytics/src/refunds/metrics/refund_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, @@ -33,7 +35,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Refund); for dim in dimensions.iter() { @@ -111,7 +113,7 @@ where i, )) }) - .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } } diff --git a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs index 661fca57b28..829b11b082c 100644 --- a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs +++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, @@ -33,7 +35,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>> + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { @@ -117,7 +119,7 @@ where i, )) }) - .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } } diff --git a/crates/analytics/src/refunds/metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/refund_success_count.rs index bc09d8b7ab6..0219340b40b 100644 --- a/crates/analytics/src/refunds/metrics/refund_success_count.rs +++ b/crates/analytics/src/refunds/metrics/refund_success_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, @@ -34,7 +36,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>> + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { @@ -115,7 +117,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>, + HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/refunds/metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/refund_success_rate.rs index 29b73b885d8..36d82385b3f 100644 --- a/crates/analytics/src/refunds/metrics/refund_success_rate.rs +++ b/crates/analytics/src/refunds/metrics/refund_success_rate.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, @@ -32,7 +34,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>> + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { @@ -110,7 +112,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>, + HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/sdk_events/metrics.rs b/crates/analytics/src/sdk_events/metrics.rs index 50481084e4b..7d5ad0c53d4 100644 --- a/crates/analytics/src/sdk_events/metrics.rs +++ b/crates/analytics/src/sdk_events/metrics.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier, @@ -29,7 +31,7 @@ use payment_methods_call_count::PaymentMethodsCallCount; use sdk_initiated_count::SdkInitiatedCount; use sdk_rendered_count::SdkRenderedCount; -#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct SdkEventMetricRow { pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, @@ -57,7 +59,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>>; + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>>; } #[async_trait::async_trait] @@ -78,7 +80,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { match self { Self::PaymentAttempts => { PaymentAttempts diff --git a/crates/analytics/src/sdk_events/metrics/average_payment_time.rs b/crates/analytics/src/sdk_events/metrics/average_payment_time.rs index 88c96d33efb..c7f6bca988c 100644 --- a/crates/analytics/src/sdk_events/metrics/average_payment_time.rs +++ b/crates/analytics/src/sdk_events/metrics/average_payment_time.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, @@ -35,7 +37,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); @@ -116,7 +118,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/sdk_events/metrics/load_time.rs b/crates/analytics/src/sdk_events/metrics/load_time.rs index 4624f304295..73cc693c506 100644 --- a/crates/analytics/src/sdk_events/metrics/load_time.rs +++ b/crates/analytics/src/sdk_events/metrics/load_time.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, @@ -35,7 +37,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); @@ -116,7 +118,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/sdk_events/metrics/payment_attempts.rs b/crates/analytics/src/sdk_events/metrics/payment_attempts.rs index 7cbe93056a9..4d949d9fb82 100644 --- a/crates/analytics/src/sdk_events/metrics/payment_attempts.rs +++ b/crates/analytics/src/sdk_events/metrics/payment_attempts.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, @@ -35,7 +37,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); @@ -111,7 +113,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs b/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs index aff78808d1d..37eb967b385 100644 --- a/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs +++ b/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, @@ -35,7 +37,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); @@ -111,7 +113,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs b/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs index 284519441a7..d524d0021cf 100644 --- a/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs +++ b/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, @@ -35,7 +37,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); @@ -111,7 +113,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs b/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs index e7dc6504036..081c4968c53 100644 --- a/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs +++ b/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, @@ -35,7 +37,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); @@ -119,7 +121,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs b/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs index 82c2096a2e4..92308acac69 100644 --- a/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs +++ b/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, @@ -35,7 +37,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); @@ -111,7 +113,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs b/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs index eba94f0d9ad..6f03008e0c1 100644 --- a/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs +++ b/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, @@ -35,7 +37,7 @@ where granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, - ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); @@ -111,7 +113,7 @@ where )) }) .collect::<error_stack::Result< - Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 816c77fd304..4323b40a887 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -44,7 +44,7 @@ pub enum TableEngine { BasicTree, } -#[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)] +#[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, Hash)] #[serde(transparent)] pub struct DBEnumWrapper<T: FromStr + Display>(pub T); diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs index 5ecdf1cecb3..32e3abaf37a 100644 --- a/crates/api_models/src/analytics/refunds.rs +++ b/crates/api_models/src/analytics/refunds.rs @@ -10,6 +10,7 @@ use crate::{enums::Currency, refunds::RefundStatus}; Copy, Debug, Default, + Hash, Eq, PartialEq, serde::Serialize, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 2ad0ad35cb3..7e320c8c367 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -25,6 +25,7 @@ pub mod diesel_exports { Copy, Debug, Default, + Hash, Eq, PartialEq, serde::Deserialize,
2024-07-02T14:36:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Used hashset instead of vector for representing the returned metrics ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 return a vector of results this causes an mismatch warning if the order is changed, instead we should use a HashSet to store & compare these values. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Using curl requests, expected normal behaviour while perfoming payments, refunds, etc ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_IG9ateOUhGE0KLFEItNN1tsJXcr5M62N7zlbtOlUtStTfPpzSomswbQa4aO2k1B4' \ --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_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" }, "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": { "data2": "camel", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` <img width="1288" alt="Screenshot 2024-07-04 at 7 42 57 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/e06f5709-d8ca-4fbc-a4ce-64059bf8088e"> <img width="640" alt="Screenshot 2024-07-04 at 7 43 31 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/0edcffbc-004f-4df8-bb8b-d98a34ec88f2"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9bc780151c8ff1874d971bf8c79ae53cb6c477d8
juspay/hyperswitch
juspay__hyperswitch-5121
Bug: [REFACTOR] Move trait IncomingWebhook to crate hyperswitch_interfaces ### Feature Description trait `IncomingWebhook` needs to be moved to crate `hyperswitch_interfaces`. This is required to move connector code to new crate `hyperswitch_connectors`. ### Possible Implementation trait `IncomingWebhook` needs to be moved to crate `hyperswitch_interfaces`. This is required to move connector code to new crate `hyperswitch_connectors`. ### 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 2c339200661..68792185b1b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3914,10 +3914,14 @@ dependencies = [ name = "hyperswitch_interfaces" version = "0.1.0" dependencies = [ + "actix-web", + "api_models", "async-trait", "bytes 1.6.0", + "common_enums", "common_utils", "dyn-clone", + "error-stack", "http 0.2.12", "hyperswitch_domain_models", "masking", diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs new file mode 100644 index 00000000000..bb768d21dd0 --- /dev/null +++ b/crates/hyperswitch_domain_models/src/api.rs @@ -0,0 +1,105 @@ +use std::fmt::Display; + +use common_utils::{ + events::{ApiEventMetric, ApiEventsType}, + impl_misc_api_event_type, +}; + +#[derive(Debug, Eq, PartialEq)] +pub enum ApplicationResponse<R> { + Json(R), + StatusOk, + TextPlain(String), + JsonForRedirection(api_models::payments::RedirectionResponse), + Form(Box<RedirectionFormData>), + PaymentLinkForm(Box<PaymentLinkAction>), + FileData((Vec<u8>, mime::Mime)), + JsonWithHeaders((R, Vec<(String, masking::Maskable<String>)>)), + GenericLinkForm(Box<GenericLinks>), +} + +impl<T: ApiEventMetric> ApiEventMetric for ApplicationResponse<T> { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + match self { + Self::Json(r) => r.get_api_event_type(), + Self::JsonWithHeaders((r, _)) => r.get_api_event_type(), + _ => None, + } + } +} + +impl_misc_api_event_type!(PaymentLinkFormData, GenericLinkFormData); + +#[derive(Debug, Eq, PartialEq)] +pub struct RedirectionFormData { + pub redirect_form: crate::router_response_types::RedirectForm, + pub payment_method_data: Option<api_models::payments::PaymentMethodData>, + pub amount: String, + pub currency: String, +} + +#[derive(Debug, Eq, PartialEq)] +pub enum PaymentLinkAction { + PaymentLinkFormData(PaymentLinkFormData), + PaymentLinkStatus(PaymentLinkStatusData), +} + +#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentLinkFormData { + pub js_script: String, + pub css_script: String, + pub sdk_url: String, + pub html_meta_tags: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentLinkStatusData { + pub js_script: String, + pub css_script: String, +} + +#[derive(Debug, Eq, PartialEq)] +pub enum GenericLinks { + ExpiredLink(GenericExpiredLinkData), + PaymentMethodCollect(GenericLinkFormData), + PayoutLink(GenericLinkFormData), + PayoutLinkStatus(GenericLinkStatusData), + PaymentMethodCollectStatus(GenericLinkStatusData), +} + +impl Display for GenericLinks { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + Self::ExpiredLink(_) => "ExpiredLink", + Self::PaymentMethodCollect(_) => "PaymentMethodCollect", + Self::PayoutLink(_) => "PayoutLink", + Self::PayoutLinkStatus(_) => "PayoutLinkStatus", + Self::PaymentMethodCollectStatus(_) => "PaymentMethodCollectStatus", + } + ) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] +pub struct GenericExpiredLinkData { + pub title: String, + pub message: String, + pub theme: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] +pub struct GenericLinkFormData { + pub js_data: String, + pub css_data: String, + pub sdk_url: String, + pub html_meta_tags: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] +pub struct GenericLinkStatusData { + pub js_data: String, + pub css_data: String, +} diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index fdafe308a45..fa3db72b08d 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -1,3 +1,4 @@ +pub mod api; pub mod errors; pub mod mandates; pub mod merchant_account; diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml index 219b50b47c2..3c481caef1b 100644 --- a/crates/hyperswitch_interfaces/Cargo.toml +++ b/crates/hyperswitch_interfaces/Cargo.toml @@ -12,9 +12,11 @@ dummy_connector = [] payouts = [] [dependencies] +actix-web = "4.5.1" async-trait = "0.1.79" bytes = "1.6.0" dyn-clone = "1.0.17" +error-stack = "0.4.1" http = "0.2.12" mime = "0.3.17" once_cell = "1.19.0" @@ -25,6 +27,8 @@ thiserror = "1.0.58" time = "0.3.35" # 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" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/hyperswitch_interfaces/src/authentication.rs b/crates/hyperswitch_interfaces/src/authentication.rs new file mode 100644 index 00000000000..960672e1d17 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/authentication.rs @@ -0,0 +1,12 @@ +//! Authentication interface + +/// struct ExternalAuthenticationPayload +#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)] +pub struct ExternalAuthenticationPayload { + /// trans_status + pub trans_status: common_enums::TransactionStatus, + /// authentication_value + pub authentication_value: Option<String>, + /// eci + pub eci: Option<String>, +} diff --git a/crates/hyperswitch_interfaces/src/disputes.rs b/crates/hyperswitch_interfaces/src/disputes.rs new file mode 100644 index 00000000000..acc7b56e906 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/disputes.rs @@ -0,0 +1,28 @@ +//! Disputes interface + +use time::PrimitiveDateTime; + +/// struct DisputePayload +#[derive(Default, Debug)] +pub struct DisputePayload { + /// amount + pub amount: String, + /// currency + pub currency: String, + /// dispute_stage + pub dispute_stage: common_enums::enums::DisputeStage, + /// connector_status + pub connector_status: String, + /// connector_dispute_id + pub connector_dispute_id: String, + /// connector_reason + pub connector_reason: Option<String>, + /// connector_reason_code + pub connector_reason_code: Option<String>, + /// challenge_required_by + pub challenge_required_by: Option<PrimitiveDateTime>, + /// created_at + pub created_at: Option<PrimitiveDateTime>, + /// updated_at + pub updated_at: Option<PrimitiveDateTime>, +} diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs index 7eb35d46a42..2acbe5c7f95 100644 --- a/crates/hyperswitch_interfaces/src/lib.rs +++ b/crates/hyperswitch_interfaces/src/lib.rs @@ -2,10 +2,12 @@ #![warn(missing_docs, missing_debug_implementations)] pub mod api; +pub mod authentication; pub mod configs; /// definition of the new connector integration trait pub mod connector_integration_v2; pub mod consts; +pub mod disputes; pub mod encryption_interface; pub mod errors; pub mod events; @@ -14,3 +16,4 @@ pub mod integrity; pub mod metrics; pub mod secrets_interface; pub mod types; +pub mod webhooks; diff --git a/crates/hyperswitch_interfaces/src/webhooks.rs b/crates/hyperswitch_interfaces/src/webhooks.rs new file mode 100644 index 00000000000..b9148d67015 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/webhooks.rs @@ -0,0 +1,229 @@ +//! Webhooks interface + +use common_utils::{crypto, errors::CustomResult, ext_traits::ValueExt}; +use error_stack::ResultExt; +use hyperswitch_domain_models::api::ApplicationResponse; +use masking::{ExposeInterface, Secret}; + +use crate::{api::ConnectorCommon, errors}; + +/// struct IncomingWebhookRequestDetails +#[derive(Debug)] +pub struct IncomingWebhookRequestDetails<'a> { + /// method + pub method: http::Method, + /// uri + pub uri: http::Uri, + /// headers + pub headers: &'a actix_web::http::header::HeaderMap, + /// body + pub body: &'a [u8], + /// query_params + pub query_params: String, +} + +/// Trait defining incoming webhook +#[async_trait::async_trait] +pub trait IncomingWebhook: ConnectorCommon + Sync { + /// fn get_webhook_body_decoding_algorithm + fn get_webhook_body_decoding_algorithm( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::NoAlgorithm)) + } + + /// fn get_webhook_body_decoding_message + fn get_webhook_body_decoding_message( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + Ok(request.body.to_vec()) + } + + /// fn decode_webhook_body + async fn decode_webhook_body( + &self, + request: &IncomingWebhookRequestDetails<'_>, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + connector_name: &str, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let algorithm = self.get_webhook_body_decoding_algorithm(request)?; + + let message = self + .get_webhook_body_decoding_message(request) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let secret = self + .get_webhook_source_verification_merchant_secret( + merchant_id, + connector_name, + connector_webhook_details, + ) + .await + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + + algorithm + .decode_message(&secret.secret, message.into()) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) + } + + /// fn get_webhook_source_verification_algorithm + fn get_webhook_source_verification_algorithm( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::NoAlgorithm)) + } + + /// fn get_webhook_source_verification_merchant_secret + async fn get_webhook_source_verification_merchant_secret( + &self, + merchant_id: &str, + connector_name: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> { + let debug_suffix = format!( + "For merchant_id: {}, and connector_name: {}", + merchant_id, connector_name + ); + let default_secret = "default_secret".to_string(); + let merchant_secret = match connector_webhook_details { + Some(merchant_connector_webhook_details) => { + let connector_webhook_details = merchant_connector_webhook_details + .parse_value::<api_models::admin::MerchantConnectorWebhookDetails>( + "MerchantConnectorWebhookDetails", + ) + .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable_lazy(|| { + format!( + "Deserializing MerchantConnectorWebhookDetails failed {}", + debug_suffix + ) + })?; + api_models::webhooks::ConnectorWebhookSecrets { + secret: connector_webhook_details + .merchant_secret + .expose() + .into_bytes(), + additional_secret: connector_webhook_details.additional_secret, + } + } + + None => api_models::webhooks::ConnectorWebhookSecrets { + secret: default_secret.into_bytes(), + additional_secret: None, + }, + }; + + //need to fetch merchant secret from config table with caching in future for enhanced performance + + //If merchant has not set the secret for webhook source verification, "default_secret" is returned. + //So it will fail during verification step and goes to psync flow. + Ok(merchant_secret) + } + + /// fn get_webhook_source_verification_signature + fn get_webhook_source_verification_signature( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + Ok(Vec::new()) + } + + /// fn get_webhook_source_verification_message + fn get_webhook_source_verification_message( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + _merchant_id: &str, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + Ok(Vec::new()) + } + + /// fn verify_webhook_source + async fn verify_webhook_source( + &self, + request: &IncomingWebhookRequestDetails<'_>, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, + connector_name: &str, + ) -> CustomResult<bool, errors::ConnectorError> { + let algorithm = self + .get_webhook_source_verification_algorithm(request) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + + let connector_webhook_secrets = self + .get_webhook_source_verification_merchant_secret( + merchant_id, + connector_name, + connector_webhook_details, + ) + .await + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + + let signature = self + .get_webhook_source_verification_signature(request, &connector_webhook_secrets) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + + let message = self + .get_webhook_source_verification_message( + request, + merchant_id, + &connector_webhook_secrets, + ) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + + algorithm + .verify_signature(&connector_webhook_secrets.secret, &signature, &message) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + } + + /// fn get_webhook_object_reference_id + fn get_webhook_object_reference_id( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError>; + + /// fn get_webhook_event_type + fn get_webhook_event_type( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError>; + + /// fn get_webhook_resource_object + fn get_webhook_resource_object( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError>; + + /// fn get_webhook_api_response + fn get_webhook_api_response( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { + Ok(ApplicationResponse::StatusOk) + } + + /// fn get_dispute_details + fn get_dispute_details( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<crate::disputes::DisputePayload, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_dispute_details method".to_string()).into()) + } + + /// fn get_external_authentication_details + fn get_external_authentication_details( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<crate::authentication::ExternalAuthenticationPayload, errors::ConnectorError> + { + Err(errors::ConnectorError::NotImplemented( + "get_external_authentication_details method".to_string(), + ) + .into()) + } +} diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index fd2fd2865a0..4fee5ea9bb0 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -7,7 +7,7 @@ use base64::Engine; use common_utils::request::RequestContent; use diesel_models::{enums as storage_enums, enums}; use error_stack::{report, ResultExt}; -use masking::ExposeInterface; +use masking::{ExposeInterface, Secret}; use ring::hmac; use router_env::{instrument, tracing}; @@ -1754,15 +1754,16 @@ impl api::IncomingWebhook for Adyen { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_label, - merchant_connector_account, + connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; @@ -1774,7 +1775,7 @@ impl api::IncomingWebhook for Adyen { let message = self .get_webhook_source_verification_message( request, - &merchant_account.merchant_id, + merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 8964c06aaf8..5115280b931 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -7,7 +7,7 @@ use base64::Engine; use common_utils::{crypto, ext_traits::XmlExt, request::RequestContent}; use diesel_models::enums; use error_stack::{report, Report, ResultExt}; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; use ring::hmac; use sha1::{Digest, Sha1}; @@ -31,7 +31,6 @@ use crate::{ types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, - domain, transformers::ForeignFrom, ErrorResponse, }, @@ -180,7 +179,7 @@ impl ConnectorValidation for Braintree { fn validate_mandate_payment( &self, pm_type: Option<types::storage::enums::PaymentMethodType>, - pm_data: domain::payments::PaymentMethodData, + pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]); connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) @@ -1377,15 +1376,16 @@ impl api::IncomingWebhook for Braintree { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_label, - merchant_connector_account, + connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; @@ -1397,7 +1397,7 @@ impl api::IncomingWebhook for Braintree { let message = self .get_webhook_source_verification_message( request, - &merchant_account.merchant_id, + merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; diff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rs index ec8c60002f0..2b06e0de69c 100644 --- a/crates/router/src/connector/cashtocode.rs +++ b/crates/router/src/connector/cashtocode.rs @@ -24,7 +24,7 @@ use crate::{ types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, - domain, storage, ErrorResponse, Response, + storage, ErrorResponse, Response, }, utils::{ByteSliceExt, BytesExt}, }; @@ -383,15 +383,16 @@ impl api::IncomingWebhook for Cashtocode { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_label, - merchant_connector_account, + connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; diff --git a/crates/router/src/connector/netcetera.rs b/crates/router/src/connector/netcetera.rs index 714873cfb53..edf56365f4e 100644 --- a/crates/router/src/connector/netcetera.rs +++ b/crates/router/src/connector/netcetera.rs @@ -5,6 +5,7 @@ use std::fmt::Debug; use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::ResultExt; +use hyperswitch_interfaces::authentication::ExternalAuthenticationPayload; use transformers as netcetera; use crate::{ @@ -203,12 +204,12 @@ impl api::IncomingWebhook for Netcetera { fn get_external_authentication_details( &self, request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::ExternalAuthenticationPayload, errors::ConnectorError> { + ) -> CustomResult<ExternalAuthenticationPayload, errors::ConnectorError> { let webhook_body: netcetera::ResultsResponseData = request .body .parse_struct("netcetera ResultsResponseData") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(api::ExternalAuthenticationPayload { + Ok(ExternalAuthenticationPayload { trans_status: webhook_body .trans_status .unwrap_or(common_enums::TransactionStatus::InformationOnly), diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs index d7a05cfa301..588ba7e712e 100644 --- a/crates/router/src/connector/payme.rs +++ b/crates/router/src/connector/payme.rs @@ -11,7 +11,7 @@ use common_utils::{ }; use diesel_models::enums; use error_stack::{Report, ResultExt}; -use masking::ExposeInterface; +use masking::{ExposeInterface, Secret}; use transformers as payme; use crate::{ @@ -1160,8 +1160,9 @@ impl api::IncomingWebhook for Payme { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let algorithm = self @@ -1170,9 +1171,9 @@ impl api::IncomingWebhook for Payme { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_label, - merchant_connector_account, + connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; @@ -1184,7 +1185,7 @@ impl api::IncomingWebhook for Payme { let mut message = self .get_webhook_source_verification_message( request, - &merchant_account.merchant_id, + merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index f4bd0997627..714f8d54626 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -9,7 +9,7 @@ use common_utils::{ }; use diesel_models::enums; use error_stack::{Report, ResultExt}; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; use rand::distributions::{Alphanumeric, DistString}; use ring::hmac; use transformers as rapyd; @@ -29,7 +29,7 @@ use crate::{ types::{ self, api::{self, ConnectorCommon}, - domain, ErrorResponse, + ErrorResponse, }, utils::{self, crypto, ByteSliceExt, BytesExt}, }; @@ -819,15 +819,16 @@ impl api::IncomingWebhook for Rapyd { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_label, - merchant_connector_account, + connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; @@ -837,7 +838,7 @@ impl api::IncomingWebhook for Rapyd { let message = self .get_webhook_source_verification_message( request, - &merchant_account.merchant_id, + merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; diff --git a/crates/router/src/connector/razorpay.rs b/crates/router/src/connector/razorpay.rs index 195508dffa2..15fac492120 100644 --- a/crates/router/src/connector/razorpay.rs +++ b/crates/router/src/connector/razorpay.rs @@ -7,7 +7,6 @@ use common_utils::{ use error_stack::{Report, ResultExt}; use masking::ExposeInterface; use transformers as razorpay; -use types::domain; use super::utils::{self as connector_utils}; use crate::{ @@ -644,8 +643,11 @@ impl api::IncomingWebhook for Razorpay { async fn verify_webhook_source( &self, _request: &api::IncomingWebhookRequestDetails<'_>, - _merchant_account: &domain::MerchantAccount, - _merchant_connector_account: domain::MerchantConnectorAccount, + _merchant_id: &str, + _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: common_utils::crypto::Encryptable< + masking::Secret<serde_json::Value>, + >, _connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { Ok(false) diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs index 28678bbd939..b37e794ec88 100644 --- a/crates/router/src/connector/riskified.rs +++ b/crates/router/src/connector/riskified.rs @@ -8,7 +8,7 @@ use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; #[cfg(feature = "frm")] use error_stack::ResultExt; #[cfg(feature = "frm")] -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "frm")] use ring::hmac; #[cfg(feature = "frm")] @@ -31,9 +31,7 @@ use crate::{ events::connector_api_logs::ConnectorEvent, headers, services::request, - types::{ - api::fraud_check as frm_api, domain, fraud_check as frm_types, ErrorResponse, Response, - }, + types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; @@ -572,15 +570,16 @@ impl api::IncomingWebhook for Riskified { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_label, - merchant_connector_account, + connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; @@ -592,7 +591,7 @@ impl api::IncomingWebhook for Riskified { let message = self .get_webhook_source_verification_message( request, - &merchant_account.merchant_id, + merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs index 9e591a336f1..c6b3e01ab5b 100644 --- a/crates/router/src/connector/signifyd.rs +++ b/crates/router/src/connector/signifyd.rs @@ -8,7 +8,7 @@ use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; #[cfg(feature = "frm")] use error_stack::ResultExt; #[cfg(feature = "frm")] -use masking::PeekInterface; +use masking::{PeekInterface, Secret}; #[cfg(feature = "frm")] use ring::hmac; #[cfg(feature = "frm")] @@ -30,9 +30,7 @@ use crate::{ use crate::{ consts, events::connector_api_logs::ConnectorEvent, - types::{ - api::fraud_check as frm_api, domain, fraud_check as frm_types, ErrorResponse, Response, - }, + types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; @@ -689,15 +687,16 @@ impl api::IncomingWebhook for Signifyd { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_label, - merchant_connector_account, + connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; @@ -709,7 +708,7 @@ impl api::IncomingWebhook for Signifyd { let message = self .get_webhook_source_verification_message( request, - &merchant_account.merchant_id, + merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs index 4604e9da872..d49a9f2b4fc 100644 --- a/crates/router/src/connector/stax.rs +++ b/crates/router/src/connector/stax.rs @@ -5,7 +5,7 @@ use std::fmt::Debug; use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; use diesel_models::enums; use error_stack::ResultExt; -use masking::PeekInterface; +use masking::{PeekInterface, Secret}; use transformers as stax; use self::stax::StaxWebhookEventType; @@ -24,7 +24,7 @@ use crate::{ types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, - domain, ErrorResponse, Response, + ErrorResponse, Response, }, utils::BytesExt, }; @@ -852,8 +852,9 @@ impl api::IncomingWebhook for Stax { async fn verify_webhook_source( &self, _request: &api::IncomingWebhookRequestDetails<'_>, - _merchant_account: &domain::MerchantAccount, - _merchant_connector_account: domain::MerchantConnectorAccount, + _merchant_id: &str, + _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>, _connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { Ok(false) diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs index b28ad2e968a..e76216f4dcd 100644 --- a/crates/router/src/connector/zen.rs +++ b/crates/router/src/connector/zen.rs @@ -4,7 +4,7 @@ use std::fmt::Debug; use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::ResultExt; -use masking::PeekInterface; +use masking::{PeekInterface, Secret}; use transformers as zen; use uuid::Uuid; @@ -608,16 +608,17 @@ impl api::IncomingWebhook for Zen { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let algorithm = self.get_webhook_source_verification_algorithm(request)?; let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_label, - merchant_connector_account, + connector_webhook_details, ) .await?; let signature = @@ -625,7 +626,7 @@ impl api::IncomingWebhook for Zen { let mut message = self.get_webhook_source_verification_message( request, - &merchant_account.merchant_id, + merchant_id, &connector_webhook_secrets, )?; let mut secret = connector_webhook_secrets.secret; diff --git a/crates/router/src/connector/zsl.rs b/crates/router/src/connector/zsl.rs index 5d5a95b0a83..f71a5e86b5d 100644 --- a/crates/router/src/connector/zsl.rs +++ b/crates/router/src/connector/zsl.rs @@ -5,7 +5,7 @@ use std::fmt::Debug; use common_utils::ext_traits::ValueExt; use diesel_models::enums; use error_stack::ResultExt; -use masking::ExposeInterface; +use masking::{ExposeInterface, Secret}; use transformers as zsl; use crate::{ @@ -418,12 +418,12 @@ impl api::IncomingWebhook for Zsl { async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, - _merchant_account: &types::domain::MerchantAccount, - merchant_connector_account: types::domain::MerchantConnectorAccount, + _merchant_id: &str, + _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>, _connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { - let connector_account_details = merchant_connector_account - .connector_account_details + let connector_account_details = connector_account_details .parse_value::<types::ConnectorAuthType>("ConnectorAuthType") .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)?; let auth_type = zsl::ZslAuthType::try_from(&connector_account_details)?; diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index b876af45dd7..44528e5c68e 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -9,6 +9,11 @@ use api_models::{ }; use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_request_types::VerifyWebhookSourceRequestData, + router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus}, +}; +use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails; use masking::ExposeInterface; use router_env::{instrument, metrics::add_attributes, tracing, tracing_actix_web::RequestId}; @@ -19,6 +24,7 @@ use crate::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments, refunds, utils as core_utils, + webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, @@ -32,7 +38,10 @@ use crate::{ ConnectorValidation, }, types::{ - api::{self, mandates::MandateResponseExt, ConnectorCommon, IncomingWebhook}, + api::{ + self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, + IncomingWebhook, + }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, @@ -129,7 +138,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( merchant_account.merchant_id.clone(), )], ); - let mut request_details = api::IncomingWebhookRequestDetails { + let mut request_details = IncomingWebhookRequestDetails { method: req.method().clone(), uri: req.uri().clone(), headers: req.headers(), @@ -150,9 +159,14 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( let decoded_body = connector .decode_webhook_body( - &*state.clone().store, &request_details, &merchant_account.merchant_id, + merchant_connector_account + .clone() + .and_then(|merchant_connector_account| { + merchant_connector_account.connector_webhook_details + }), + connector_name.as_str(), ) .await .switch() @@ -258,30 +272,32 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( .connectors_with_webhook_source_verification_call .contains(&connector_enum) { - connector - .verify_webhook_source_verification_call( - &state, - &merchant_account, - merchant_connector_account.clone(), - &connector_name, - &request_details, - ) - .await - .or_else(|error| match error.current_context() { - errors::ConnectorError::WebhookSourceVerificationFailed => { - logger::error!(?error, "Source Verification Failed"); - Ok(false) - } - _ => Err(error), - }) - .switch() - .attach_printable("There was an issue in incoming webhook source verification")? + verify_webhook_source_verification_call( + connector.clone(), + &state, + &merchant_account, + merchant_connector_account.clone(), + &connector_name, + &request_details, + ) + .await + .or_else(|error| match error.current_context() { + errors::ConnectorError::WebhookSourceVerificationFailed => { + logger::error!(?error, "Source Verification Failed"); + Ok(false) + } + _ => Err(error), + }) + .switch() + .attach_printable("There was an issue in incoming webhook source verification")? } else { connector + .clone() .verify_webhook_source( &request_details, - &merchant_account, - merchant_connector_account.clone(), + &merchant_account.merchant_id, + merchant_connector_account.connector_webhook_details.clone(), + merchant_connector_account.connector_account_details.clone(), connector_name.as_str(), ) .await @@ -970,7 +986,7 @@ async fn external_authentication_incoming_webhook_flow( key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, - request_details: &api::IncomingWebhookRequestDetails<'_>, + request_details: &IncomingWebhookRequestDetails<'_>, connector: &ConnectorEnum, object_ref_id: api::ObjectReferenceId, business_profile: diesel_models::business_profile::BusinessProfile, @@ -1346,7 +1362,7 @@ async fn disputes_incoming_webhook_flow( webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, - request_details: &api::IncomingWebhookRequestDetails<'_>, + request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]); @@ -1534,6 +1550,66 @@ async fn get_payment_id( .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } +#[inline] +async fn verify_webhook_source_verification_call( + connector: ConnectorEnum, + state: &SessionState, + merchant_account: &domain::MerchantAccount, + merchant_connector_account: domain::MerchantConnectorAccount, + connector_name: &str, + request_details: &IncomingWebhookRequestDetails<'_>, +) -> CustomResult<bool, errors::ConnectorError> { + let connector_data = ConnectorData::get_connector_by_name( + &state.conf.connectors, + connector_name, + GetToken::Connector, + None, + ) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("invalid connector name received in payment attempt")?; + let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface< + hyperswitch_domain_models::router_flow_types::VerifyWebhookSource, + VerifyWebhookSourceRequestData, + VerifyWebhookSourceResponseData, + > = connector_data.connector.get_connector_integration(); + let connector_webhook_secrets = connector + .get_webhook_source_verification_merchant_secret( + &merchant_account.merchant_id, + connector_name, + merchant_connector_account.connector_webhook_details.clone(), + ) + .await + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + + let router_data = construct_webhook_router_data( + connector_name, + merchant_connector_account, + merchant_account, + &connector_webhook_secrets, + request_details, + ) + .await + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Failed while constructing webhook router data")?; + + let response = services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await?; + + let verification_result = response + .response + .map(|response| response.verify_webhook_status); + match verification_result { + Ok(VerifyWebhookStatus::SourceVerified) => Ok(true), + _ => Ok(false), + } +} + fn get_connector_by_connector_name( state: &SessionState, connector_name: &str, @@ -1562,10 +1638,10 @@ fn get_connector_by_connector_name( authentication_connector_data.connector_name.to_string(), ) } else { - let connector_data = api::ConnectorData::get_connector_by_name( + let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, - api::GetToken::Connector, + GetToken::Connector, merchant_connector_id, ) .change_context(errors::ApiErrorResponse::InvalidRequestData { diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs index 6da8d697ac2..7bf66dd0951 100644 --- a/crates/router/src/events/api_logs.rs +++ b/crates/router/src/events/api_logs.rs @@ -15,10 +15,7 @@ use crate::routes::dummy_connector::types::{ }; use crate::{ core::payments::PaymentsRedirectResponseData, - services::{ - authentication::AuthenticationType, kafka::KafkaMessage, ApplicationResponse, - GenericLinkFormData, PaymentLinkFormData, - }, + services::{authentication::AuthenticationType, kafka::KafkaMessage}, types::api::{ AttachEvidenceRequest, Config, ConfigUpdate, CreateFileRequest, DisputeId, FileId, PollId, }, @@ -101,22 +98,11 @@ impl KafkaMessage for ApiEvent { } } -impl<T: ApiEventMetric> ApiEventMetric for ApplicationResponse<T> { - fn get_api_event_type(&self) -> Option<ApiEventsType> { - match self { - Self::Json(r) => r.get_api_event_type(), - Self::JsonWithHeaders((r, _)) => r.get_api_event_type(), - _ => None, - } - } -} impl_misc_api_event_type!( Config, CreateFileRequest, FileId, AttachEvidenceRequest, - PaymentLinkFormData, - GenericLinkFormData, ConfigUpdate ); diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 8de3a5ca4dd..d65def0c97a 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -4,7 +4,7 @@ pub mod request; use std::{ collections::{HashMap, HashSet}, error::Error, - fmt::{Debug, Display}, + fmt::Debug, future::Future, str, sync::Arc, @@ -26,7 +26,14 @@ use common_utils::{ }; use error_stack::{report, Report, ResultExt}; use hyperswitch_domain_models::router_data_v2::flow_common_types as common_types; -pub use hyperswitch_domain_models::router_response_types::RedirectForm; +pub use hyperswitch_domain_models::{ + api::{ + ApplicationResponse, GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, + GenericLinks, PaymentLinkAction, PaymentLinkFormData, PaymentLinkStatusData, + RedirectionFormData, + }, + router_response_types::RedirectForm, +}; pub use hyperswitch_interfaces::{ api::{ BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration, ConnectorIntegrationAny, @@ -713,93 +720,6 @@ async fn handle_response( .await } -#[derive(Debug, Eq, PartialEq)] -pub enum ApplicationResponse<R> { - Json(R), - StatusOk, - TextPlain(String), - JsonForRedirection(api::RedirectionResponse), - Form(Box<RedirectionFormData>), - PaymentLinkForm(Box<PaymentLinkAction>), - FileData((Vec<u8>, mime::Mime)), - JsonWithHeaders((R, Vec<(String, Maskable<String>)>)), - GenericLinkForm(Box<GenericLinks>), -} - -#[derive(Debug, Eq, PartialEq)] -pub enum GenericLinks { - ExpiredLink(GenericExpiredLinkData), - PaymentMethodCollect(GenericLinkFormData), - PayoutLink(GenericLinkFormData), - PayoutLinkStatus(GenericLinkStatusData), - PaymentMethodCollectStatus(GenericLinkStatusData), -} - -impl Display for Box<GenericLinks> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "{}", - match **self { - GenericLinks::ExpiredLink(_) => "ExpiredLink", - GenericLinks::PaymentMethodCollect(_) => "PaymentMethodCollect", - GenericLinks::PayoutLink(_) => "PayoutLink", - GenericLinks::PayoutLinkStatus(_) => "PayoutLinkStatus", - GenericLinks::PaymentMethodCollectStatus(_) => "PaymentMethodCollectStatus", - } - ) - } -} - -#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] -pub struct GenericLinkFormData { - pub js_data: String, - pub css_data: String, - pub sdk_url: String, - pub html_meta_tags: String, -} - -#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] -pub struct GenericExpiredLinkData { - pub title: String, - pub message: String, - pub theme: String, -} - -#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] -pub struct GenericLinkStatusData { - pub js_data: String, - pub css_data: String, -} - -#[derive(Debug, Eq, PartialEq)] -pub enum PaymentLinkAction { - PaymentLinkFormData(PaymentLinkFormData), - PaymentLinkStatus(PaymentLinkStatusData), -} - -#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] -pub struct PaymentLinkFormData { - pub js_script: String, - pub css_script: String, - pub sdk_url: String, - pub html_meta_tags: String, -} - -#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] -pub struct PaymentLinkStatusData { - pub js_script: String, - pub css_script: String, -} - -#[derive(Debug, Eq, PartialEq)] -pub struct RedirectionFormData { - pub redirect_form: RedirectForm, - pub payment_method_data: Option<api::PaymentMethodData>, - pub amount: String, - pub currency: String, -} - #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, diff --git a/crates/router/src/services/connector_integration_interface.rs b/crates/router/src/services/connector_integration_interface.rs index 8b6bdf50e1c..8af9d0b58c3 100644 --- a/crates/router/src/services/connector_integration_interface.rs +++ b/crates/router/src/services/connector_integration_interface.rs @@ -1,13 +1,14 @@ use common_utils::{crypto, errors::CustomResult, request::Request}; use hyperswitch_domain_models::{router_data::RouterData, router_data_v2::RouterDataV2}; -use hyperswitch_interfaces::connector_integration_v2::ConnectorIntegrationV2; +use hyperswitch_interfaces::{ + authentication::ExternalAuthenticationPayload, connector_integration_v2::ConnectorIntegrationV2, +}; use super::{BoxedConnectorIntegrationV2, ConnectorValidation}; use crate::{ core::payments, errors, events::connector_api_logs::ConnectorEvent, - routes::app::StorageInterface, services::{ api as services_api, BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration, ConnectorRedirectResponse, PaymentAction, @@ -16,8 +17,8 @@ use crate::{ types::{ self, api::{ - self, disputes, Connector, ConnectorV2, CurrencyUnit, ExternalAuthenticationPayload, - IncomingWebhookEvent, IncomingWebhookRequestDetails, ObjectReferenceId, + self, disputes, Connector, ConnectorV2, CurrencyUnit, IncomingWebhookEvent, + IncomingWebhookRequestDetails, ObjectReferenceId, }, domain, }, @@ -99,25 +100,6 @@ impl api::IncomingWebhook for ConnectorEnum { } } - async fn get_webhook_body_decoding_merchant_secret( - &self, - db: &dyn StorageInterface, - merchant_id: &str, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - match self { - Self::Old(connector) => { - connector - .get_webhook_body_decoding_merchant_secret(db, merchant_id) - .await - } - Self::New(connector) => { - connector - .get_webhook_body_decoding_merchant_secret(db, merchant_id) - .await - } - } - } - fn get_webhook_body_decoding_message( &self, request: &IncomingWebhookRequestDetails<'_>, @@ -130,19 +112,30 @@ impl api::IncomingWebhook for ConnectorEnum { async fn decode_webhook_body( &self, - db: &dyn StorageInterface, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + connector_name: &str, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => { connector - .decode_webhook_body(db, request, merchant_id) + .decode_webhook_body( + request, + merchant_id, + connector_webhook_details, + connector_name, + ) .await } Self::New(connector) => { connector - .decode_webhook_body(db, request, merchant_id) + .decode_webhook_body( + request, + merchant_id, + connector_webhook_details, + connector_name, + ) .await } } @@ -160,26 +153,26 @@ impl api::IncomingWebhook for ConnectorEnum { async fn get_webhook_source_verification_merchant_secret( &self, - merchant_account: &domain::MerchantAccount, + merchant_id: &str, connector_name: &str, - merchant_connector_account: domain::MerchantConnectorAccount, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> { match self { Self::Old(connector) => { connector .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_name, - merchant_connector_account, + connector_webhook_details, ) .await } Self::New(connector) => { connector .get_webhook_source_verification_merchant_secret( - merchant_account, + merchant_id, connector_name, - merchant_connector_account, + connector_webhook_details, ) .await } @@ -219,45 +212,12 @@ impl api::IncomingWebhook for ConnectorEnum { } } - async fn verify_webhook_source_verification_call( - &self, - state: &crate::routes::SessionState, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, - connector_name: &str, - request_details: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<bool, errors::ConnectorError> { - match self { - Self::Old(connector) => { - connector - .verify_webhook_source_verification_call( - state, - merchant_account, - merchant_connector_account, - connector_name, - request_details, - ) - .await - } - Self::New(connector) => { - connector - .verify_webhook_source_verification_call( - state, - merchant_account, - merchant_connector_account, - connector_name, - request_details, - ) - .await - } - } - } - async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, + merchant_id: &str, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>, connector_name: &str, ) -> CustomResult<bool, errors::ConnectorError> { match self { @@ -265,8 +225,9 @@ impl api::IncomingWebhook for ConnectorEnum { connector .verify_webhook_source( request, - merchant_account, - merchant_connector_account, + merchant_id, + connector_webhook_details, + connector_account_details, connector_name, ) .await @@ -275,8 +236,9 @@ impl api::IncomingWebhook for ConnectorEnum { connector .verify_webhook_source( request, - merchant_account, - merchant_connector_account, + merchant_id, + connector_webhook_details, + connector_account_details, connector_name, ) .await diff --git a/crates/router/src/types/api/authentication.rs b/crates/router/src/types/api/authentication.rs index 3a39e06fde9..9b2a69bfe0c 100644 --- a/crates/router/src/types/api/authentication.rs +++ b/crates/router/src/types/api/authentication.rs @@ -74,13 +74,6 @@ pub struct PostAuthenticationResponse { pub eci: Option<String>, } -#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)] -pub struct ExternalAuthenticationPayload { - pub trans_status: common_enums::TransactionStatus, - pub authentication_value: Option<String>, - pub eci: Option<String>, -} - pub trait ConnectorAuthentication: services::ConnectorIntegration< Authentication, diff --git a/crates/router/src/types/api/disputes.rs b/crates/router/src/types/api/disputes.rs index 72a899c3b97..247b8bf45e3 100644 --- a/crates/router/src/types/api/disputes.rs +++ b/crates/router/src/types/api/disputes.rs @@ -1,5 +1,5 @@ +pub use hyperswitch_interfaces::disputes::DisputePayload; use masking::{Deserialize, Serialize}; -use time::PrimitiveDateTime; use crate::{services, types}; @@ -12,20 +12,6 @@ pub use hyperswitch_domain_models::router_flow_types::dispute::{Accept, Defend, pub use super::disputes_v2::{AcceptDisputeV2, DefendDisputeV2, DisputeV2, SubmitEvidenceV2}; -#[derive(Default, Debug)] -pub struct DisputePayload { - pub amount: String, - pub currency: String, - pub dispute_stage: api_models::enums::DisputeStage, - pub connector_status: String, - pub connector_dispute_id: String, - pub connector_reason: Option<String>, - pub connector_reason_code: Option<String>, - pub challenge_required_by: Option<PrimitiveDateTime>, - pub created_at: Option<PrimitiveDateTime>, - pub updated_at: Option<PrimitiveDateTime>, -} - #[derive(Default, Debug, Deserialize, Serialize)] pub struct DisputeEvidence { pub cancellation_policy: Option<String>, diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rs index cc37cb8d7bc..490ff29640c 100644 --- a/crates/router/src/types/api/webhooks.rs +++ b/crates/router/src/types/api/webhooks.rs @@ -1,282 +1,5 @@ -use api_models::admin::MerchantConnectorWebhookDetails; pub use api_models::webhooks::{ AuthenticationIdType, IncomingWebhookDetails, IncomingWebhookEvent, MerchantWebhookConfig, ObjectReferenceId, OutgoingWebhook, OutgoingWebhookContent, WebhookFlow, }; -use common_utils::ext_traits::ValueExt; -use error_stack::ResultExt; -use masking::ExposeInterface; - -use super::ConnectorCommon; -use crate::{ - core::{ - errors::{self, CustomResult}, - payments, - webhooks::utils::construct_webhook_router_data, - }, - db::StorageInterface, - services::{self}, - types::{self, domain}, - utils::crypto, -}; - -pub struct IncomingWebhookRequestDetails<'a> { - pub method: actix_web::http::Method, - pub uri: actix_web::http::Uri, - pub headers: &'a actix_web::http::header::HeaderMap, - pub body: &'a [u8], - pub query_params: String, -} - -#[async_trait::async_trait] -pub trait IncomingWebhook: ConnectorCommon + Sync { - fn get_webhook_body_decoding_algorithm( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> { - Ok(Box::new(crypto::NoAlgorithm)) - } - - async fn get_webhook_body_decoding_merchant_secret( - &self, - _db: &dyn StorageInterface, - _merchant_id: &str, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - Ok(Vec::new()) - } - - fn get_webhook_body_decoding_message( - &self, - request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - Ok(request.body.to_vec()) - } - - async fn decode_webhook_body( - &self, - db: &dyn StorageInterface, - request: &IncomingWebhookRequestDetails<'_>, - merchant_id: &str, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let algorithm = self.get_webhook_body_decoding_algorithm(request)?; - - let message = self - .get_webhook_body_decoding_message(request) - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - let secret = self - .get_webhook_body_decoding_merchant_secret(db, merchant_id) - .await - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - - algorithm - .decode_message(&secret, message.into()) - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) - } - - fn get_webhook_source_verification_algorithm( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { - Ok(Box::new(crypto::NoAlgorithm)) - } - - async fn get_webhook_source_verification_merchant_secret( - &self, - merchant_account: &domain::MerchantAccount, - connector_name: &str, - merchant_connector_account: domain::MerchantConnectorAccount, - ) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> { - let merchant_id = merchant_account.merchant_id.as_str(); - let debug_suffix = format!( - "For merchant_id: {}, and connector_name: {}", - merchant_id, connector_name - ); - let default_secret = "default_secret".to_string(); - let merchant_secret = match merchant_connector_account.connector_webhook_details { - Some(merchant_connector_webhook_details) => { - let connector_webhook_details = merchant_connector_webhook_details - .parse_value::<MerchantConnectorWebhookDetails>( - "MerchantConnectorWebhookDetails", - ) - .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed) - .attach_printable_lazy(|| { - format!( - "Deserializing MerchantConnectorWebhookDetails failed {}", - debug_suffix - ) - })?; - api_models::webhooks::ConnectorWebhookSecrets { - secret: connector_webhook_details - .merchant_secret - .expose() - .into_bytes(), - additional_secret: connector_webhook_details.additional_secret, - } - } - - None => api_models::webhooks::ConnectorWebhookSecrets { - secret: default_secret.into_bytes(), - additional_secret: None, - }, - }; - - //need to fetch merchant secret from config table with caching in future for enhanced performance - - //If merchant has not set the secret for webhook source verification, "default_secret" is returned. - //So it will fail during verification step and goes to psync flow. - Ok(merchant_secret) - } - - fn get_webhook_source_verification_signature( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - Ok(Vec::new()) - } - - fn get_webhook_source_verification_message( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - _merchant_id: &str, - _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - Ok(Vec::new()) - } - - async fn verify_webhook_source_verification_call( - &self, - state: &crate::routes::SessionState, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, - connector_name: &str, - request_details: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<bool, errors::ConnectorError> { - let connector_data = types::api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - connector_name, - types::api::GetToken::Connector, - None, - ) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) - .attach_printable("invalid connector name received in payment attempt")?; - let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface< - types::api::VerifyWebhookSource, - types::VerifyWebhookSourceRequestData, - types::VerifyWebhookSourceResponseData, - > = connector_data.connector.get_connector_integration(); - let connector_webhook_secrets = self - .get_webhook_source_verification_merchant_secret( - merchant_account, - connector_name, - merchant_connector_account.clone(), - ) - .await - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - - let router_data = construct_webhook_router_data( - connector_name, - merchant_connector_account, - merchant_account, - &connector_webhook_secrets, - request_details, - ) - .await - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) - .attach_printable("Failed while constructing webhook router data")?; - - let response = services::execute_connector_processing_step( - state, - connector_integration, - &router_data, - payments::CallConnectorAction::Trigger, - None, - ) - .await?; - - let verification_result = response - .response - .map(|response| response.verify_webhook_status); - match verification_result { - Ok(types::VerifyWebhookStatus::SourceVerified) => Ok(true), - _ => Ok(false), - } - } - - async fn verify_webhook_source( - &self, - request: &IncomingWebhookRequestDetails<'_>, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: domain::MerchantConnectorAccount, - connector_name: &str, - ) -> CustomResult<bool, errors::ConnectorError> { - let algorithm = self - .get_webhook_source_verification_algorithm(request) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - - let connector_webhook_secrets = self - .get_webhook_source_verification_merchant_secret( - merchant_account, - connector_name, - merchant_connector_account, - ) - .await - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - - let signature = self - .get_webhook_source_verification_signature(request, &connector_webhook_secrets) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - - let message = self - .get_webhook_source_verification_message( - request, - &merchant_account.merchant_id, - &connector_webhook_secrets, - ) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - - algorithm - .verify_signature(&connector_webhook_secrets.secret, &signature, &message) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) - } - - fn get_webhook_object_reference_id( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<ObjectReferenceId, errors::ConnectorError>; - - fn get_webhook_event_type( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError>; - - fn get_webhook_resource_object( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError>; - - fn get_webhook_api_response( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError> - { - Ok(services::api::ApplicationResponse::StatusOk) - } - - fn get_dispute_details( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<super::disputes::DisputePayload, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_dispute_details method".to_string()).into()) - } - - fn get_external_authentication_details( - &self, - _request: &IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<super::ExternalAuthenticationPayload, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented( - "get_external_authentication_details method".to_string(), - ) - .into()) - } -} +pub use hyperswitch_interfaces::webhooks::{IncomingWebhook, IncomingWebhookRequestDetails};
2024-07-03T09:59:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> trait `IncomingWebhook` is moved to crate `hyperswitch_interfaces`. This is required for moving connector code to new crate `hyperswitch_connectors`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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/5121 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Webhooks need to be tested for production connectors like adyen, stripe, cryptopay, etc. Scenarios like wrong `connector_webhook_details.merchant_secret` also need to be tested. <img width="1227" alt="Screenshot 2024-07-11 at 4 09 49 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/6f4750f0-5b99-4105-b8ea-2493ba24b8c7"> <img width="1231" alt="Screenshot 2024-07-11 at 4 09 34 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/6919b7a4-c7e3-4f3a-8a85-d7f765b55d0b"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
66ac1584dfd6e8574732cb753bdce0136d36c205
juspay/hyperswitch
juspay__hyperswitch-5079
Bug: avoid considering pre-routing results during `perform_session_token_routing` avoid considering pre-routing results during `perform_session_token_routing` As there is a logic to filter out the apple pay payment method if apple pay is already saved. But this should not be the save when performing the session token (`perform_session_token_routing`).
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a8fe21796b5..fd052163c4b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3653,57 +3653,61 @@ pub async fn perform_session_token_routing<F>( where F: Clone, { - let routing_info: Option<storage::PaymentRoutingInfo> = payment_data - .payment_attempt - .straight_through_algorithm - .clone() - .map(|val| val.parse_value("PaymentRoutingInfo")) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("invalid payment routing info format found in payment attempt")?; - - if let Some(storage::PaymentRoutingInfo { - pre_routing_results: Some(pre_routing_results), - .. - }) = routing_info - { - let mut payment_methods: rustc_hash::FxHashMap< - (String, enums::PaymentMethodType), - api::SessionConnectorData, - > = rustc_hash::FxHashMap::from_iter(connectors.iter().map(|c| { - ( - ( - c.connector.connector_name.to_string(), - c.payment_method_type, - ), - c.clone(), - ) - })); - - let mut final_list: Vec<api::SessionConnectorData> = Vec::new(); - for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() { - let routable_connector_list = match pre_routing_choice { - storage::PreRoutingConnectorChoice::Single(routable_connector) => { - vec![routable_connector.clone()] - } - storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { - routable_connector_list.clone() - } - }; - for routable_connector in routable_connector_list { - if let Some(session_connector_data) = - payment_methods.remove(&(routable_connector.to_string(), routed_pm_type)) - { - final_list.push(session_connector_data); - break; - } - } - } - - if !final_list.is_empty() { - return Ok(final_list); - } - } + // Commenting out this code as `list_payment_method_api` and `perform_session_token_routing` + // will happen in parallel the behaviour of the session call differ based on filters in + // list_payment_method_api + + // let routing_info: Option<storage::PaymentRoutingInfo> = payment_data + // .payment_attempt + // .straight_through_algorithm + // .clone() + // .map(|val| val.parse_value("PaymentRoutingInfo")) + // .transpose() + // .change_context(errors::ApiErrorResponse::InternalServerError) + // .attach_printable("invalid payment routing info format found in payment attempt")?; + + // if let Some(storage::PaymentRoutingInfo { + // pre_routing_results: Some(pre_routing_results), + // .. + // }) = routing_info + // { + // let mut payment_methods: rustc_hash::FxHashMap< + // (String, enums::PaymentMethodType), + // api::SessionConnectorData, + // > = rustc_hash::FxHashMap::from_iter(connectors.iter().map(|c| { + // ( + // ( + // c.connector.connector_name.to_string(), + // c.payment_method_type, + // ), + // c.clone(), + // ) + // })); + + // let mut final_list: Vec<api::SessionConnectorData> = Vec::new(); + // for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() { + // let routable_connector_list = match pre_routing_choice { + // storage::PreRoutingConnectorChoice::Single(routable_connector) => { + // vec![routable_connector.clone()] + // } + // storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + // routable_connector_list.clone() + // } + // }; + // for routable_connector in routable_connector_list { + // if let Some(session_connector_data) = + // payment_methods.remove(&(routable_connector.to_string(), routed_pm_type)) + // { + // final_list.push(session_connector_data); + // break; + // } + // } + // } + + // if !final_list.is_empty() { + // return Ok(final_list); + // } + // } let routing_enabled_pms = HashSet::from([ enums::PaymentMethodType::GooglePay,
2024-06-21T16:51:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> avoid considering pre-routing results during `perform_session_token_routing` As there is a logic to filter out the apple pay payment method if apple pay is already saved. But this should not be the save when performing the session token (`perform_session_token_routing`). https://github.com/juspay/hyperswitch/pull/5076 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create mca with apple pay configured -> Create payment with apple pay ``` { "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "test_fb", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiVnJnTm9mYXRRZEFIME1MTjZjd1VMazdIS09PdWIvUnMwbEtFOW1vWllvcFhSSXpGemM4VDJiMzlpWjdWSGVXK0YxZVFmY0V5OFJrWjMvcWRZQkVyaE4wK1BxL2pRZ2xpZFNUNlYzdXNwRHB6MlJGSWxYUWhiODJndmd5Y3hSb1R6MER4MDgwNzQ1MUJkN1RMUldyVWNlaVRvdEN4N041ZXFVcjM3UTJlZ2hTaExNOWtXVzAxSmIvT3FLM3RLTUhZaFZNRmE2alNaaHduMVU1NitpbXR5SDMvS1BpdlJlQ0ZxTUtFVmJiRFRyNmpzSDEyNWUwVmlOalBXYm1kVzZJZWU2RDR0cjk5VEhiSkhiWUJzaVdrMUROb29tS28zbHRVUjRkMTZwL09Cc2xTYUh6dnFTL2VrOGVCTDB4dTB3TkMyamx5OFpQUnVZNGRZL2gyS3U0VmprL1BpTWtJUnRNVGl3MTFZWExXUHFNamkvM1N1VDcxUEFnZllpQU4zZmxYK1Q5RmVZRE5yVmdSNWFyRGN3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWt3Z2dHRkFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUdWJsaWNLZXkiOiJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVZQTdEUmxFWjk4KzNYNjVnTWVEam5wVndOS1FxRytnTzhlQmJaUDBWVVNyOFZ3ckx5YXZ4cW9ua1dJc01ZemhVRVpJYjJjZGxYd3c0eGJFRis1S25uQT09IiwidHJhbnNhY3Rpb25JZCI6ImMxMTFjYzA1YzBkZjFiMjZmYTI3MjcwZDcyMjhmM2EzNDQ1ZTJhMDNiYTMyYjQ5NjI3ODEzNTVkYjc2M2VjNjMifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` <img width="1057" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c6ebf1b6-6325-4c96-a923-2687e0acccb8"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ca61e47585071865cf7df5c05fdbe3f57818ca95
juspay/hyperswitch
juspay__hyperswitch-5077
Bug: avoid considering pre-routing results during `perform_session_token_routing` avoid considering pre-routing results during `perform_session_token_routing` As there is a logic to filter out the apple pay payment method if apple pay is already saved. But this should not be the save when performing the session token (`perform_session_token_routing`).
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a8fe21796b5..fd052163c4b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3653,57 +3653,61 @@ pub async fn perform_session_token_routing<F>( where F: Clone, { - let routing_info: Option<storage::PaymentRoutingInfo> = payment_data - .payment_attempt - .straight_through_algorithm - .clone() - .map(|val| val.parse_value("PaymentRoutingInfo")) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("invalid payment routing info format found in payment attempt")?; - - if let Some(storage::PaymentRoutingInfo { - pre_routing_results: Some(pre_routing_results), - .. - }) = routing_info - { - let mut payment_methods: rustc_hash::FxHashMap< - (String, enums::PaymentMethodType), - api::SessionConnectorData, - > = rustc_hash::FxHashMap::from_iter(connectors.iter().map(|c| { - ( - ( - c.connector.connector_name.to_string(), - c.payment_method_type, - ), - c.clone(), - ) - })); - - let mut final_list: Vec<api::SessionConnectorData> = Vec::new(); - for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() { - let routable_connector_list = match pre_routing_choice { - storage::PreRoutingConnectorChoice::Single(routable_connector) => { - vec![routable_connector.clone()] - } - storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { - routable_connector_list.clone() - } - }; - for routable_connector in routable_connector_list { - if let Some(session_connector_data) = - payment_methods.remove(&(routable_connector.to_string(), routed_pm_type)) - { - final_list.push(session_connector_data); - break; - } - } - } - - if !final_list.is_empty() { - return Ok(final_list); - } - } + // Commenting out this code as `list_payment_method_api` and `perform_session_token_routing` + // will happen in parallel the behaviour of the session call differ based on filters in + // list_payment_method_api + + // let routing_info: Option<storage::PaymentRoutingInfo> = payment_data + // .payment_attempt + // .straight_through_algorithm + // .clone() + // .map(|val| val.parse_value("PaymentRoutingInfo")) + // .transpose() + // .change_context(errors::ApiErrorResponse::InternalServerError) + // .attach_printable("invalid payment routing info format found in payment attempt")?; + + // if let Some(storage::PaymentRoutingInfo { + // pre_routing_results: Some(pre_routing_results), + // .. + // }) = routing_info + // { + // let mut payment_methods: rustc_hash::FxHashMap< + // (String, enums::PaymentMethodType), + // api::SessionConnectorData, + // > = rustc_hash::FxHashMap::from_iter(connectors.iter().map(|c| { + // ( + // ( + // c.connector.connector_name.to_string(), + // c.payment_method_type, + // ), + // c.clone(), + // ) + // })); + + // let mut final_list: Vec<api::SessionConnectorData> = Vec::new(); + // for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() { + // let routable_connector_list = match pre_routing_choice { + // storage::PreRoutingConnectorChoice::Single(routable_connector) => { + // vec![routable_connector.clone()] + // } + // storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + // routable_connector_list.clone() + // } + // }; + // for routable_connector in routable_connector_list { + // if let Some(session_connector_data) = + // payment_methods.remove(&(routable_connector.to_string(), routed_pm_type)) + // { + // final_list.push(session_connector_data); + // break; + // } + // } + // } + + // if !final_list.is_empty() { + // return Ok(final_list); + // } + // } let routing_enabled_pms = HashSet::from([ enums::PaymentMethodType::GooglePay,
2024-06-21T15:52:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> avoid considering pre-routing results during `perform_session_token_routing` As there is a logic to filter out the apple pay payment method if apple pay is already saved. But this should not be the save when performing the session token (`perform_session_token_routing`). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create mca with apple pay configured -> Create payment with apple pay ``` { "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "test_fb", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiVnJnTm9mYXRRZEFIME1MTjZjd1VMazdIS09PdWIvUnMwbEtFOW1vWllvcFhSSXpGemM4VDJiMzlpWjdWSGVXK0YxZVFmY0V5OFJrWjMvcWRZQkVyaE4wK1BxL2pRZ2xpZFNUNlYzdXNwRHB6MlJGSWxYUWhiODJndmd5Y3hSb1R6MER4MDgwNzQ1MUJkN1RMUldyVWNlaVRvdEN4N041ZXFVcjM3UTJlZ2hTaExNOWtXVzAxSmIvT3FLM3RLTUhZaFZNRmE2alNaaHduMVU1NitpbXR5SDMvS1BpdlJlQ0ZxTUtFVmJiRFRyNmpzSDEyNWUwVmlOalBXYm1kVzZJZWU2RDR0cjk5VEhiSkhiWUJzaVdrMUROb29tS28zbHRVUjRkMTZwL09Cc2xTYUh6dnFTL2VrOGVCTDB4dTB3TkMyamx5OFpQUnVZNGRZL2gyS3U0VmprL1BpTWtJUnRNVGl3MTFZWExXUHFNamkvM1N1VDcxUEFnZllpQU4zZmxYK1Q5RmVZRE5yVmdSNWFyRGN3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWt3Z2dHRkFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUdWJsaWNLZXkiOiJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVZQTdEUmxFWjk4KzNYNjVnTWVEam5wVndOS1FxRytnTzhlQmJaUDBWVVNyOFZ3ckx5YXZ4cW9ua1dJc01ZemhVRVpJYjJjZGxYd3c0eGJFRis1S25uQT09IiwidHJhbnNhY3Rpb25JZCI6ImMxMTFjYzA1YzBkZjFiMjZmYTI3MjcwZDcyMjhmM2EzNDQ1ZTJhMDNiYTMyYjQ5NjI3ODEzNTVkYjc2M2VjNjMifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` <img width="1057" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c6ebf1b6-6325-4c96-a923-2687e0acccb8"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
6a07e10af379006c4643bb8f0a9cb2f46813ff8a
juspay/hyperswitch
juspay__hyperswitch-5070
Bug: [FEATURE] Populate status code and delivery attempt information in outgoing webhooks ClickHouse events ### Description As of opening this issue, the outgoing webhooks ClickHouse events contain a few fields: https://github.com/juspay/hyperswitch/blob/ca61e47585071865cf7df5c05fdbe3f57818ca95/crates/router/src/events/outgoing_webhook_logs.rs#L11-L21 There are `error` and `is_error` fields that indicate whether an error occurred when delivering the webhook to the merchant server, but do not include any information on whether the merchant server even received the webhook. To address this issue, we must include the following optional fields in the ClickHouse events: - `status_code` - `delivery_attempt` - `initial_attempt_id` The fields would have to be added in the `OutgoingWebhookEvent` struct, and the corresponding columns must be added in the ClickHouse table. Once the fields have been added in code, the fields must be populated from the [`Event` in the database](https://github.com/juspay/hyperswitch/blob/ca61e47585071865cf7df5c05fdbe3f57818ca95/crates/router/src/types/domain/event.rs#L15-L31): - The `delivery_attempt` and `initial_attempt_id` are available directly in the `Event` struct. - The `status_code` field is available within the `response` struct, if the webhook was delivered to the merchant server.
diff --git a/crates/analytics/docs/clickhouse/scripts/outgoing_webhook_events.sql b/crates/analytics/docs/clickhouse/scripts/outgoing_webhook_events.sql index 30f3f293bfa..a104bc506fd 100644 --- a/crates/analytics/docs/clickhouse/scripts/outgoing_webhook_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/outgoing_webhook_events.sql @@ -12,6 +12,9 @@ CREATE TABLE outgoing_webhook_events_queue ( `content` Nullable(String), `is_error` Bool, `error` Nullable(String), + `initial_attempt_id` Nullable(String), + `status_code` Nullable(UInt16), + `delivery_attempt` LowCardinality(String), `created_at_timestamp` DateTime64(3) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-outgoing-webhook-events', @@ -33,6 +36,9 @@ CREATE TABLE outgoing_webhook_events ( `content` Nullable(String), `is_error` Bool, `error` Nullable(String), + `initial_attempt_id` Nullable(String), + `status_code` Nullable(UInt16), + `delivery_attempt` LowCardinality(String), `created_at` DateTime64(3), `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), INDEX eventIndex event_type TYPE bloom_filter GRANULARITY 1, @@ -61,6 +67,9 @@ CREATE TABLE outgoing_webhook_events_audit ( `content` Nullable(String), `is_error` Bool, `error` Nullable(String), + `initial_attempt_id` Nullable(String), + `status_code` Nullable(UInt16), + `delivery_attempt` LowCardinality(String), `created_at` DateTime64(3), `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4) ) ENGINE = MergeTree PARTITION BY merchant_id @@ -81,6 +90,9 @@ CREATE MATERIALIZED VIEW outgoing_webhook_events_mv TO outgoing_webhook_events ( `content` Nullable(String), `is_error` Bool, `error` Nullable(String), + `initial_attempt_id` Nullable(String), + `status_code` Nullable(UInt16), + `delivery_attempt` LowCardinality(String), `created_at` DateTime64(3), `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4) ) AS @@ -98,6 +110,9 @@ SELECT content, is_error, error, + initial_attempt_id, + status_code, + delivery_attempt, created_at_timestamp AS created_at, now() AS inserted_at FROM @@ -119,6 +134,9 @@ CREATE MATERIALIZED VIEW outgoing_webhook_events_audit_mv TO outgoing_webhook_ev `content` Nullable(String), `is_error` Bool, `error` Nullable(String), + `initial_attempt_id` Nullable(String), + `status_code` Nullable(UInt16), + `delivery_attempt` LowCardinality(String), `created_at` DateTime64(3), `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4) ) AS @@ -136,6 +154,9 @@ SELECT content, is_error, error, + initial_attempt_id, + status_code, + delivery_attempt, created_at_timestamp AS created_at, now() AS inserted_at FROM diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index 25c93f8465e..79a23259794 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -5,7 +5,10 @@ use api_models::{ webhooks, }; use common_utils::{ - ext_traits::Encode, request::RequestContent, type_name, types::keymanager::Identifier, + ext_traits::{Encode, StringExt}, + request::RequestContent, + type_name, + types::keymanager::{Identifier, KeyManagerState}, }; use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; @@ -33,7 +36,8 @@ use crate::{ routes::{app::SessionStateInfo, SessionState}, services, types::{ - api, domain, + api, + domain::{self}, storage::{self, enums}, transformers::ForeignFrom, }, @@ -226,7 +230,15 @@ pub(crate) async fn trigger_webhook_and_raise_event( ) .await; - raise_webhooks_analytics_event(state, trigger_webhook_result, content, merchant_id, event); + let _ = raise_webhooks_analytics_event( + state, + trigger_webhook_result, + content, + merchant_id, + event, + merchant_key_store, + ) + .await; } async fn trigger_webhook_to_merchant( @@ -436,13 +448,17 @@ async fn trigger_webhook_to_merchant( Ok(()) } -fn raise_webhooks_analytics_event( +async fn raise_webhooks_analytics_event( state: SessionState, trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>, content: Option<api::OutgoingWebhookContent>, merchant_id: common_utils::id_type::MerchantId, event: domain::Event, + merchant_key_store: &domain::MerchantKeyStore, ) { + let key_manager_state: &KeyManagerState = &(&state).into(); + let event_id = event.event_id; + let error = if let Err(error) = trigger_webhook_result { logger::error!(?error, "Failed to send webhook to merchant"); @@ -462,13 +478,47 @@ fn raise_webhooks_analytics_event( .and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content) .or_else(|| get_outgoing_webhook_event_content_from_event_metadata(event.metadata)); + // Fetch updated_event from db + let updated_event = state + .store + .find_event_by_merchant_id_event_id( + key_manager_state, + &merchant_id, + &event_id, + merchant_key_store, + ) + .await + .attach_printable_lazy(|| format!("event not found for id: {}", &event_id)) + .map_err(|error| { + logger::error!(?error); + error + }) + .ok(); + + // Get status_code from webhook response + let status_code = updated_event.and_then(|updated_event| { + let webhook_response: Option<OutgoingWebhookResponseContent> = + updated_event.response.and_then(|res| { + res.peek() + .parse_struct("OutgoingWebhookResponseContent") + .map_err(|error| { + logger::error!(?error, "Error deserializing webhook response"); + error + }) + .ok() + }); + webhook_response.and_then(|res| res.status_code) + }); + let webhook_event = OutgoingWebhookEvent::new( merchant_id, - event.event_id, + event_id, event.event_type, outgoing_webhook_event_content, error, event.initial_attempt_id, + status_code, + event.delivery_attempt, ); state.event_handler().log_event(&webhook_event); } diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs index 7ab100c2503..2a56f60ecac 100644 --- a/crates/router/src/events/outgoing_webhook_logs.rs +++ b/crates/router/src/events/outgoing_webhook_logs.rs @@ -1,4 +1,5 @@ use api_models::{enums::EventType as OutgoingWebhookEventType, webhooks::OutgoingWebhookContent}; +use common_enums::WebhookDeliveryAttempt; use serde::Serialize; use serde_json::Value; use time::OffsetDateTime; @@ -18,6 +19,8 @@ pub struct OutgoingWebhookEvent { error: Option<Value>, created_at_timestamp: i128, initial_attempt_id: Option<String>, + status_code: Option<u16>, + delivery_attempt: Option<WebhookDeliveryAttempt>, } #[derive(Clone, Debug, PartialEq, Serialize)] @@ -89,6 +92,7 @@ impl OutgoingWebhookEventMetric for OutgoingWebhookContent { } impl OutgoingWebhookEvent { + #[allow(clippy::too_many_arguments)] pub fn new( merchant_id: common_utils::id_type::MerchantId, event_id: String, @@ -96,6 +100,8 @@ impl OutgoingWebhookEvent { content: Option<OutgoingWebhookEventContent>, error: Option<Value>, initial_attempt_id: Option<String>, + status_code: Option<u16>, + delivery_attempt: Option<WebhookDeliveryAttempt>, ) -> Self { Self { merchant_id, @@ -106,6 +112,8 @@ impl OutgoingWebhookEvent { error, created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, initial_attempt_id, + status_code, + delivery_attempt, } } }
2024-07-21T10:21:48Z
## Type of Change - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Closes #5070. This PR enhances the outgoing_webhook_events and outgoing_webhook_events_audit tables by adding three new columns: initial_attempt_id, status_code, and delivery_attempt. These additions are essential for tracking the initial_attempt_id, status_code, and delivery_attempt status for outgoing webhook events, allowing for more detailed monitoring and troubleshooting of webhook deliveries to merchant servers. ### Database Schema Changes On Clickhouse Please run the following `ALTER TABLE` commands to update the database schema: #### `outgoing_webhook_events` Table ```sql ALTER TABLE outgoing_webhook_events ADD COLUMN initial_attempt_id Nullable(String), ADD COLUMN status_code Nullable(UInt16), ADD COLUMN delivery_attempt LowCardinality(String); ``` #### `outgoing_webhook_events_audit` Table ```sql ALTER TABLE outgoing_webhook_events_audit ADD COLUMN initial_attempt_id Nullable(String), ADD COLUMN status_code Nullable(UInt16), ADD COLUMN delivery_attempt LowCardinality(String); ``` ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## How did you test it? Tested locally. <img width="2052" alt="outgoing_webhook_events" src="https://github.com/user-attachments/assets/6f04c804-bfc3-40b8-9d6c-49aca0abadc5"> <img width="2055" alt="outgoing_webhook_events_audit" src="https://github.com/user-attachments/assets/9c453d2f-3cbe-4a9a-88f3-446715115dd9"> ## Checklist - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
1715cf0ed4c67e87fe3ddf9090174fc70d6c9e8c
juspay/hyperswitch
juspay__hyperswitch-5069
Bug: Paypal webhook disputes
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 456332ea0f1..ee6b6c818c5 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -1465,7 +1465,6 @@ impl self, req, connectors, )?) .build(); - Ok(Some(request)) } @@ -1546,11 +1545,11 @@ impl api::IncomingWebhook for Paypal { } paypal::PaypalResource::PaypalDisputeWebhooks(resource) => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::PaymentAttemptId( + api_models::payments::PaymentIdType::ConnectorTransactionId( resource - .dispute_transactions + .disputed_transactions .first() - .map(|transaction| transaction.reference_id.clone()) + .map(|transaction| transaction.seller_transaction_id.clone()) .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, ), )) @@ -1567,17 +1566,17 @@ impl api::IncomingWebhook for Paypal { .parse_struct("PaypalWebooksEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; let outcome = match payload.event_type { - PaypalWebhookEventType::CustomerDisputeCreated - | PaypalWebhookEventType::CustomerDisputeResolved - | PaypalWebhookEventType::CustomerDisputedUpdated - | PaypalWebhookEventType::RiskDisputeCreated => Some( + PaypalWebhookEventType::CustomerDisputeResolved => Some( request .body .parse_struct::<paypal::DisputeOutcome>("PaypalWebooksEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)? .outcome_code, ), - PaypalWebhookEventType::PaymentAuthorizationCreated + PaypalWebhookEventType::CustomerDisputeCreated + | PaypalWebhookEventType::RiskDisputeCreated + | PaypalWebhookEventType::CustomerDisputedUpdated + | PaypalWebhookEventType::PaymentAuthorizationCreated | PaypalWebhookEventType::PaymentAuthorizationVoided | PaypalWebhookEventType::PaymentCaptureDeclined | PaypalWebhookEventType::PaymentCaptureCompleted @@ -1622,27 +1621,37 @@ impl api::IncomingWebhook for Paypal { &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> { - let payload: paypal::PaypalDisputeWebhooks = request + let webhook_payload: paypal::PaypalWebhooksBody = request .body - .parse_struct("PaypalDisputeWebhooks") + .parse_struct("PaypalWebhooksBody") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(api::disputes::DisputePayload { - amount: connector_utils::to_currency_lower_unit( - payload.dispute_amount.value.get_amount_as_string(), - payload.dispute_amount.currency_code, - )?, - currency: payload.dispute_amount.currency_code.to_string(), - dispute_stage: api_models::enums::DisputeStage::from( - payload.dispute_life_cycle_stage.clone(), - ), - connector_status: payload.status.to_string(), - connector_dispute_id: payload.dispute_id, - connector_reason: payload.reason, - connector_reason_code: payload.external_reason_code, - challenge_required_by: payload.seller_response_due_date, - created_at: payload.create_time, - updated_at: payload.update_time, - }) + match webhook_payload.resource { + transformers::PaypalResource::PaypalCardWebhooks(_) + | transformers::PaypalResource::PaypalRedirectsWebhooks(_) + | transformers::PaypalResource::PaypalRefundWebhooks(_) => { + Err(errors::ConnectorError::ResponseDeserializationFailed) + .attach_printable("Expected Dispute webhooks,but found other webhooks")? + } + transformers::PaypalResource::PaypalDisputeWebhooks(payload) => { + Ok(api::disputes::DisputePayload { + amount: connector_utils::to_currency_lower_unit( + payload.dispute_amount.value.get_amount_as_string(), + payload.dispute_amount.currency_code, + )?, + currency: payload.dispute_amount.currency_code.to_string(), + dispute_stage: api_models::enums::DisputeStage::from( + payload.dispute_life_cycle_stage.clone(), + ), + connector_status: payload.status.to_string(), + connector_dispute_id: payload.dispute_id, + connector_reason: payload.reason.clone(), + connector_reason_code: payload.reason, + challenge_required_by: None, + created_at: payload.create_time, + updated_at: payload.update_time, + }) + } + } } } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index c12c7d5da15..39ea808d61f 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -1980,7 +1980,7 @@ pub struct OrderErrorDetails { #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PaypalOrderErrorResponse { - pub name: String, + pub name: Option<String>, pub message: String, pub debug_id: Option<String>, pub details: Option<Vec<OrderErrorDetails>>, @@ -1994,7 +1994,7 @@ pub struct ErrorDetails { #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PaypalPaymentErrorResponse { - pub name: String, + pub name: Option<String>, pub message: String, pub debug_id: Option<String>, pub details: Option<Vec<ErrorDetails>>, @@ -2056,21 +2056,24 @@ pub enum PaypalResource { #[derive(Deserialize, Debug, Serialize)] pub struct PaypalDisputeWebhooks { pub dispute_id: String, - pub dispute_transactions: Vec<DisputeTransaction>, + pub disputed_transactions: Vec<DisputeTransaction>, pub dispute_amount: OrderAmount, - pub dispute_outcome: DisputeOutcome, + pub dispute_outcome: Option<DisputeOutcome>, pub dispute_life_cycle_stage: DisputeLifeCycleStage, pub status: DisputeStatus, pub reason: Option<String>, pub external_reason_code: Option<String>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub seller_response_due_date: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub update_time: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub create_time: Option<PrimitiveDateTime>, } #[derive(Deserialize, Debug, Serialize)] pub struct DisputeTransaction { - pub reference_id: String, + pub seller_transaction_id: String, } #[derive(Clone, Deserialize, Debug, strum::Display, Serialize)]
2024-06-25T00:11:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This refactored branch resolves the PayPal dispute webhook deserialization issue. -> It was failing to identify the webhook entity type and object reference ID. -> I updated the fields accordingly to resolve the deserialization issue. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Motivation https://github.com/juspay/hyperswitch/issues/5069 there are some filed refactors included which resolved the problem <!-- 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). --> ## How did you test it? I ran the ngrok for frowarding webhook payload to localhost with url (https://697b-219-65-110-2.ngrok-free.app/webhooks/merchant_1719300138/paypal) I have created dispute webhook through paypal simulator and these are the logs : Incoming webhook Payload: ``` { "id": "WH-4M0448861G563140B-9EX36365822141321", "create_time": "2018-06-21T13:36:33.000Z", "resource_type": "dispute", "event_type": "CUSTOMER.DISPUTE.CREATED", "summary": "A new dispute opened with Case # PP-000-042-663-135", "resource": { "disputed_transactions": [ { "seller_transaction_id": "00D10444LD479031K", "seller": { "merchant_id": "RD465XN5VS364", "name": "Test Store" }, "items": [], "seller_protection_eligible": true } ], "reason": "MERCHANDISE_OR_SERVICE_NOT_RECEIVED", "dispute_channel": "INTERNAL", "update_time": "2018-06-21T13:35:44.000Z", "create_time": "2018-06-21T13:35:44.000Z", "messages": [ { "posted_by": "BUYER", "time_posted": "2018-06-21T13:35:52.000Z", "content": "qwqwqwq" } ], "links": [ { "href": "https://api.paypal.com/v1/customer/disputes/PP-000-042-663-135", "rel": "self", "method": "GET" }, { "href": "https://api.paypal.com/v1/customer/disputes/PP-000-042-663-135/send-message", "rel": "send_message", "method": "POST" } ], "dispute_amount": { "currency_code": "USD", "value": "3.00" }, "dispute_id": "PP-000-042-663-135", "dispute_life_cycle_stage": "INQUIRY", "status": "OPEN" }, "links": [ { "href": "https://api.paypal.com/v1/notifications/webhooks-events/WH-4M0448861G563140B-9EX36365822141321", "rel": "self", "method": "GET", "encType": "application/json" }, { "href": "https://api.paypal.com/v1/notifications/webhooks-events/WH-4M0448861G563140B-9EX36365822141321/resend", "rel": "resend", "method": "POST", "encType": "application/json" } ], "event_version": "1.0" } ``` Dispute Creation: <img width="1232" alt="image" src="https://github.com/juspay/hyperswitch/assets/60121719/d264c5dc-6a85-4c97-bb8f-4b83a5c88f48"> Source Verification: Due to these are Mock events , we cant verify them through Paypal so I have done source verification as true to check further flows like Database record creation and triggering outgoing webhooks. Database Record Creation: <img width="1208" alt="image" src="https://github.com/juspay/hyperswitch/assets/60121719/dd0db6ae-5fd1-4e5c-b2a8-e12d30d2eb47"> Outgoing Webhook Response Payload: ``` { "merchant_id": "merchant_1719481316", "event_id": "evt_0190594e16ab7f38abd50ca6f32707b9", "event_type": "dispute_opened", "content": { "type": "dispute_details", "object": { "dispute_id": "dp_rgC7BN7DQRQ9YlksqCmO", "payment_id": "pay_qW4qVbLZXOO1GQsd0mQ3", "attempt_id": "00D10444LD479031K", "amount": "300", "currency": "USD", "dispute_stage": "pre_dispute", "dispute_status": "dispute_opened", "connector": "paypal", "connector_status": "Open", "connector_dispute_id": "PP-000-042-663-135", "connector_reason": "MERCHANDISE_OR_SERVICE_NOT_RECEIVED", "connector_reason_code": "MERCHANDISE_OR_SERVICE_NOT_RECEIVED", "challenge_required_by": null, "connector_created_at": "2018-06-21T13:35:44.000Z", "connector_updated_at": "2018-06-21T13:35:44.000Z", "created_at": "2024-06-27T10:46:48.214Z", "profile_id": "pro_AKqLxMihwY7h8QqvuPfH", "merchant_connector_id": "mca_q1lwLDnNEPzyGvClsHsR" } }, "timestamp": "2024-06-27T10:46:48.235Z" } ``` <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ecc6c00d4aaa034f96eae76c64024d56bb5fa173
juspay/hyperswitch
juspay__hyperswitch-5086
Bug: [REFACTORE] : Connector Metadata,ApplePay and GooglePay ### Feature Description Current WASM structure for the ApplePay,GooglePay and MetaData was not extendable for the additional fields. In the case of ApplePay, all user input field changes are happening for **session_token_data**. With the current structure, all fields are considered text inputs. If we want to show a select box or toggle field, the connector team needs to reach out to the dashboard team for the respective changes. To avoid this dependency, the connector team will now be able to add different fields based on requirements themselves. One such example is **merchant_business_country**, where the input field needs to be a select box. However, due to the current structure, the connector team is not able to add the field and needs to inform the dashboard team for the update. In the case of GooglePay, the request structure is a bit complicated, as the user only needs to enter **merchant_id**, **merchant_name**, and **gateway_merchant_id**, while the rest of the data remains constant. Previously, the idea was to send these fields to WebAssembly (WASM) and construct the request there, but this created more complications in both the frontend and backend. Therefore, we decided to construct the request on the frontend itself and fetch only the input fields from WASM. Metadata fields also have the same issue as **merchant_business_country**, where only **text** input fields are accepted with the current structure. To add a **toggle** or **select** field, the connector team needs to reach out to the dashboard team for the changes. With the modified structure, this dependency is resolved. When does the dependency comes? For ApplePay, current changes are happening at **session_token_data**. When changes need to happen at a different level, for example, if a merchant wants to change the supported_networks themselves, which is under **payment_request_data**, a dependency arises. They need to inform the dashboard team, which will then map the name of the field. Similar for googlePay and metadata fields. <img width="839" alt="image" src="https://github.com/juspay/hyperswitch-control-center/assets/120017870/ee40a9fb-562b-42a9-9988-84042deceaf1"> **Modified WASM structure for ApplePay,GooglePay and MetaData** ``` [[adyen.metadata.apple_pay_v2]] name="certificate" label="Merchant Certificate (Base64 Encoded)" placeholder="Enter Merchant Certificate (Base64 Encoded)" required=true type="Text" [[adyen.metadata.apple_pay_v2]] name="certificate_keys" label="Merchant PrivateKey (Base64 Encoded)" placeholder="Enter Merchant PrivateKey (Base64 Encoded)" required=true type="Text" [[adyen.metadata.apple_pay_v2]] name="merchant_identifier" label="Apple Merchant Identifier" placeholder="Enter Apple Merchant Identifier" required=true type="Text" [[adyen.metadata.apple_pay_v2]] name="display_name" label="Display Name" placeholder="Enter Display Name" required=true type="Text" [[adyen.metadata.apple_pay_v2]] name="initiative" label="Domain" placeholder="Enter Domain" required=true type="Text" [[adyen.metadata.apple_pay_v2]] name="initiative_context" label="Domain Name" placeholder="Enter Domain Name" required=true type="Text" [[adyen.metadata.apple_pay_v2]] name="merchant_business_country" label="Merchant Business Country" placeholder="Enter Merchant Business Country" required=true type="Select" options=[] [[adyen.metadata.apple_pay_v2]] name="payment_processing_details_at" label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" options=["Connector","Hyperswitch"] [[adyen.metadata.google_pay]] name="merchant_name" label="Google Pay Merchant Name" placeholder="Enter Google Pay Merchant Name" required=true type="Text" [[adyen.metadata.google_pay]] name="merchant_id" label="Google Pay Merchant Id" placeholder="Enter Google Pay Merchant Id" required=true type="Text" [[adyen.metadata.google_pay]] name="gateway_merchant_id" label="Google Pay Merchant Key" placeholder="Enter Google Pay Merchant Key" required=true type="Text" [adyen.metadata.endpoint_prefix] name="endpoint_prefix" label="Live endpoint prefix" placeholder="Enter Live endpoint prefix" required=true type="Text" ``` **Current WASM structure for ApplePay,GooglePay and MetaData** ``` [adyen.metadata.apple_pay.session_token_data] certificate="Merchant Certificate (Base64 Encoded)" certificate_keys="Merchant PrivateKey (Base64 Encoded)" merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" payment_processing_details_at="Connector" [adyen.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] label="apple" [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" merchant_id="Google Pay Merchant ID" [adyen.metadata] endpoint_prefix="Live endpoint prefix" ``` **Apple Pay Request Structure for Manual** ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "xxxxxxxx-initiative", "certificate": "xxxxxx-certificate", "display_name": "xxxxxx-display_name", "certificate_keys": "xxxxxx-certificate_keys", "initiative_context": "xxxxxx-initiative_context", "merchant_identifier": "xxxxxx-merchant_identifier", "merchant_business_country": "LV", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "xxxxxx-payment_processing_certificate", "payment_processing_certificate_key": "xxxxxx-payment_processing_certificate_key" }, "payment_request_data": { "label": "apple", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` **Apple Pay Request Structure for Simplified** ``` "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "https://google.com", "merchant_business_country": "DE" }, "payment_request_data": { "label": "apple", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` **GooglePay Request Structure** ``` "google_pay": { "merchant_info": { "merchant_id": "xxxx-merchant_id", "merchant_name": "xxxx-merchant_name" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "adyen", "gateway_merchant_id": "xxxx-gateway_merchant_id" } } } ] } ``` **List of Apple Pay and GooglePay Connectors** 1. adyen 2. authorizedotnet 3. bankofamerica 4. bluesnap 5. checkout 6. cybersource 7. nmi 8. noon 9. nuvei 10. stripe 11. trustpay 12. worldpay 13. zen **Testing command** ``` ["adyen","authorizedotnet","bankofamerica","bluesnap","checkout","cybersource","nmi","noon","nuvei","stripe","trustpay","worldpay","zen"].forEach(ele=>{ console.log(ele,window.getConnectorConfig(ele).metadata) }) ``` **List of Apple Pay Connectors** 1. nexinets 2. rapyd **Testing command** ``` ["nexinets","rapyd"].forEach(ele=>{ console.log(ele,window.getConnectorConfig(ele).metadata) }) ``` **List of Google Pay Connectors** 1. airwallex 2. globalpay 4. multisafepay 5. payu **Testing command** ``` ["airwallex","globalpay","multisafepay","payu"].forEach(ele=>{ console.log(ele,window.getConnectorConfig(ele).metadata) }) ``` **List of metadata field changes** 1. merchant_config_currency (braintree) 2. merchant_account_id (braintree) 3. account_name (globalpay) 4. terminal_id (fiserv) 5. merchant_id (bluesnap) 6. endpoint_prefix (adyen,adyen_payout,netcetera) 7. mcc (threedssecurio,netcetera) 8. merchant_country_code (threedssecurio,netcetera) 9. merchant_name (threedssecurio,netcetera) 10. acquirer_bin (checkout,cybersource,nmi) 11. acquirer_merchant_id (checkout,cybersource,nmi) 12. acquirer_country_code (checkout,cybersource,nmi) 13. three_ds_requestor_name (netcetera) 14. three_ds_requestor_id (netcetera) 15. pull_mechanism_for_external_3ds_enabled (threedssecurio) 16. klarna_region (klarna) 17. source_balance_account (adyenplatform_payout) 18. brand_id (mifinity) **Production Connectors to Test Apple Pay And GooglePay** 1. adyen 2. authorizedotnet 3. bluesnap 4. bankofamerica 5. checkout 6. cybersource 7. nexinets (has only applePay) 8. rapyd (has only applePay) 9. stripe 10. trustpay 11. worldpay 12. payu (has only googlePay) 13. zen 14. globalpay (has only googlePay) ``` ["adyen","authorizedotnet","bluesnap","bankofamerica","checkout","cybersource","nexinets","rapyd","stripe","trustpay","worldpay","payu","zen","globalpay"].forEach(ele=>{ console.log(ele,window.getConnectorConfig(ele).metadata) }) ``` **Production Metadata** 1. merchant_config_currency (braintree) 2. merchant_account_id (braintree) 3. account_name (globalpay) 4. terminal_id (fiserv) 5. merchant_id (bluesnap) 6. endpoint_prefix (adyen) 7. klarna_region (klarna) 8. brand_id (mifinity) Examples to consider klarna_region ### Possible Implementation Updated the wasm structure ### 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/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index 837f0985b8f..88b8165853d 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -189,34 +189,28 @@ pub struct DashboardPaymentMethodPayload { pub struct DashboardRequestPayload { pub connector: api_models::enums::Connector, pub payment_methods_enabled: Option<Vec<DashboardPaymentMethodPayload>>, - pub metadata: Option<DashboardMetaData>, + pub metadata: Option<ApiModelMetaData>, +} + +#[serde_with::skip_serializing_none] +#[derive(Debug, Deserialize, serde::Serialize, Clone)] +#[serde(tag = "type", content = "options")] +pub enum InputType { + Text, + Toggle, + Radio(Vec<String>), + Select(Vec<String>), + MultiSelect(Vec<String>), } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(rename_all = "snake_case")] -pub struct DashboardMetaData { - pub merchant_config_currency: Option<api_models::enums::Currency>, - pub merchant_account_id: Option<String>, - pub account_name: Option<String>, - pub terminal_id: Option<String>, - pub merchant_id: Option<String>, - pub google_pay: Option<GooglePayData>, - pub paypal_sdk: Option<PaypalSdkData>, - pub apple_pay: Option<ApplePayData>, - pub apple_pay_combined: Option<ApplePayData>, - pub endpoint_prefix: Option<String>, - pub mcc: Option<String>, - pub merchant_country_code: Option<String>, - pub merchant_name: Option<String>, - pub acquirer_bin: Option<String>, - pub acquirer_merchant_id: Option<String>, - pub acquirer_country_code: Option<String>, - pub three_ds_requestor_name: Option<String>, - pub three_ds_requestor_id: Option<String>, - pub pull_mechanism_for_external_3ds_enabled: Option<bool>, - pub klarna_region: Option<KlarnaEndpoint>, - pub source_balance_account: Option<String>, - pub brand_id: Option<String>, - pub destination_account_number: Option<String>, +pub struct MetaDataInupt { + pub name: String, + pub label: String, + pub placeholder: String, + pub required: bool, + #[serde(flatten)] + pub input_type: InputType, } diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index baa606f82c1..b314194485c 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -10,7 +10,7 @@ use serde::Deserialize; #[cfg(any(feature = "sandbox", feature = "development", feature = "production"))] use toml; -use crate::common_config::{CardProvider, GooglePayData, PaypalSdkData, Provider, ZenApplePay}; +use crate::common_config::{CardProvider, MetaDataInupt, Provider, ZenApplePay}; #[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct Classic { @@ -83,28 +83,27 @@ pub enum KlarnaEndpoint { #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] pub struct ConfigMetadata { - pub merchant_config_currency: Option<String>, - pub merchant_account_id: Option<String>, - pub account_name: Option<String>, - pub terminal_id: Option<String>, - pub google_pay: Option<GooglePayData>, - pub paypal_sdk: Option<PaypalSdkData>, - pub apple_pay: Option<ApplePayTomlConfig>, - pub merchant_id: Option<String>, - pub endpoint_prefix: Option<String>, - pub mcc: Option<String>, - pub merchant_country_code: Option<String>, - pub merchant_name: Option<String>, - pub acquirer_bin: Option<String>, - pub acquirer_merchant_id: Option<String>, - pub acquirer_country_code: Option<String>, - pub three_ds_requestor_name: Option<String>, - pub three_ds_requestor_id: Option<String>, - pub pull_mechanism_for_external_3ds_enabled: Option<bool>, - pub klarna_region: Option<Vec<KlarnaEndpoint>>, - pub source_balance_account: Option<String>, - pub brand_id: Option<String>, - pub destination_account_number: Option<String>, + pub merchant_config_currency: Option<MetaDataInupt>, + pub merchant_account_id: Option<MetaDataInupt>, + pub account_name: Option<MetaDataInupt>, + pub terminal_id: Option<MetaDataInupt>, + pub google_pay: Option<Vec<MetaDataInupt>>, + pub apple_pay: Option<Vec<MetaDataInupt>>, + pub merchant_id: Option<MetaDataInupt>, + pub endpoint_prefix: Option<MetaDataInupt>, + pub mcc: Option<MetaDataInupt>, + pub merchant_country_code: Option<MetaDataInupt>, + pub merchant_name: Option<MetaDataInupt>, + pub acquirer_bin: Option<MetaDataInupt>, + pub acquirer_merchant_id: Option<MetaDataInupt>, + pub acquirer_country_code: Option<MetaDataInupt>, + pub three_ds_requestor_name: Option<MetaDataInupt>, + pub three_ds_requestor_id: Option<MetaDataInupt>, + pub pull_mechanism_for_external_3ds_enabled: Option<MetaDataInupt>, + pub klarna_region: Option<MetaDataInupt>, + pub source_balance_account: Option<MetaDataInupt>, + pub brand_id: Option<MetaDataInupt>, + pub destination_account_number: Option<MetaDataInupt>, } #[serde_with::skip_serializing_none] @@ -112,7 +111,7 @@ pub struct ConfigMetadata { pub struct ConnectorTomlConfig { pub connector_auth: Option<ConnectorAuthType>, pub connector_webhook_details: Option<api_models::admin::MerchantConnectorWebhookDetails>, - pub metadata: Option<ConfigMetadata>, + pub metadata: Option<Box<ConfigMetadata>>, pub credit: Option<Vec<CardProvider>>, pub debit: Option<Vec<CardProvider>>, pub bank_transfer: Option<Vec<Provider>>, diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs index 20eeef5f463..38dc4130cf0 100644 --- a/crates/connector_configs/src/response_modifier.rs +++ b/crates/connector_configs/src/response_modifier.rs @@ -1,7 +1,6 @@ use crate::common_config::{ - ApiModelMetaData, CardProvider, ConnectorApiIntegrationPayload, DashboardMetaData, - DashboardPaymentMethodPayload, DashboardRequestPayload, GoogleApiModelData, GooglePayData, - GpayDashboardPayLoad, Provider, + CardProvider, ConnectorApiIntegrationPayload, DashboardPaymentMethodPayload, + DashboardRequestPayload, Provider, }; impl ConnectorApiIntegrationPayload { @@ -307,8 +306,6 @@ impl ConnectorApiIntegrationPayload { card_provider: Some(credit_details), }; - let meta_data = response.metadata.map(DashboardMetaData::from); - DashboardRequestPayload { connector: response.connector_name, payment_methods_enabled: Some(vec![ @@ -327,62 +324,7 @@ impl ConnectorApiIntegrationPayload { credit_details, gift_card, ]), - metadata: meta_data, - } - } -} - -impl From<ApiModelMetaData> for DashboardMetaData { - fn from(api_model: ApiModelMetaData) -> Self { - Self { - merchant_config_currency: api_model.merchant_config_currency, - merchant_account_id: api_model.merchant_account_id, - account_name: api_model.account_name, - terminal_id: api_model.terminal_id, - merchant_id: api_model.merchant_id, - google_pay: get_google_pay_metadata_response(api_model.google_pay), - paypal_sdk: api_model.paypal_sdk, - apple_pay: api_model.apple_pay, - apple_pay_combined: api_model.apple_pay_combined, - endpoint_prefix: api_model.endpoint_prefix, - mcc: api_model.mcc, - merchant_country_code: api_model.merchant_country_code, - merchant_name: api_model.merchant_name, - acquirer_bin: api_model.acquirer_bin, - acquirer_merchant_id: api_model.acquirer_merchant_id, - acquirer_country_code: api_model.acquirer_country_code, - three_ds_requestor_name: api_model.three_ds_requestor_name, - three_ds_requestor_id: api_model.three_ds_requestor_id, - pull_mechanism_for_external_3ds_enabled: api_model - .pull_mechanism_for_external_3ds_enabled, - klarna_region: api_model.klarna_region, - source_balance_account: api_model.source_balance_account, - brand_id: api_model.brand_id, - destination_account_number: api_model.destination_account_number, + metadata: response.metadata, } } } - -pub fn get_google_pay_metadata_response( - google_pay_data: Option<GoogleApiModelData>, -) -> Option<GooglePayData> { - match google_pay_data { - Some(google_pay) => match google_pay { - GoogleApiModelData::Standard(standard_data) => { - let data = standard_data - .allowed_payment_methods - .first() - .map(|allowed_pm| allowed_pm.tokenization_specification.parameters.clone())?; - Some(GooglePayData::Standard(GpayDashboardPayLoad { - gateway_merchant_id: data.gateway_merchant_id, - stripe_version: data.stripe_version, - stripe_publishable_key: data.stripe_publishable_key, - merchant_name: standard_data.merchant_info.merchant_name, - merchant_id: standard_data.merchant_info.merchant_id, - })) - } - GoogleApiModelData::Zen(data) => Some(GooglePayData::Zen(data)), - }, - None => None, - } -} diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 6f71d14ec07..1a54dc9ae0d 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -5,13 +5,12 @@ use api_models::{ Connector, PaymentMethod, PaymentMethodType::{self, AliPay, ApplePay, GooglePay, Klarna, Paypal, WeChatPay}, }, - payment_methods, payments, + payment_methods, refunds::MinorUnit, }; use crate::common_config::{ - ApiModelMetaData, ConnectorApiIntegrationPayload, DashboardMetaData, DashboardRequestPayload, - GoogleApiModelData, GooglePayData, PaymentMethodsEnabled, Provider, + ConnectorApiIntegrationPayload, DashboardRequestPayload, PaymentMethodsEnabled, Provider, }; impl DashboardRequestPayload { @@ -166,7 +165,6 @@ impl DashboardRequestPayload { } } - let metadata = Self::transform_metedata(request); ConnectorApiIntegrationPayload { connector_type: api_response.connector_type, profile_id: api_response.profile_id, @@ -177,163 +175,7 @@ impl DashboardRequestPayload { test_mode: api_response.test_mode, payment_methods_enabled: Some(payment_method_enabled), connector_webhook_details: api_response.connector_webhook_details, - metadata, - } - } - - pub fn transform_metedata(request: Self) -> Option<ApiModelMetaData> { - let default_metadata = DashboardMetaData { - apple_pay_combined: None, - google_pay: None, - apple_pay: None, - account_name: None, - terminal_id: None, - merchant_account_id: None, - merchant_id: None, - merchant_config_currency: None, - endpoint_prefix: None, - mcc: None, - merchant_country_code: None, - merchant_name: None, - acquirer_bin: None, - acquirer_merchant_id: None, - acquirer_country_code: None, - three_ds_requestor_name: None, - three_ds_requestor_id: None, - pull_mechanism_for_external_3ds_enabled: None, - paypal_sdk: None, - klarna_region: None, - source_balance_account: None, - brand_id: None, - destination_account_number: None, - }; - let meta_data = match request.metadata { - Some(data) => data, - None => default_metadata, - }; - let google_pay = Self::get_google_pay_details(meta_data.clone(), request.connector); - let account_name = meta_data.account_name.clone(); - let merchant_account_id = meta_data.merchant_account_id.clone(); - let merchant_id = meta_data.merchant_id.clone(); - let terminal_id = meta_data.terminal_id.clone(); - let endpoint_prefix = meta_data.endpoint_prefix.clone(); - let paypal_sdk = meta_data.paypal_sdk; - let apple_pay = meta_data.apple_pay; - let apple_pay_combined = meta_data.apple_pay_combined; - let merchant_config_currency = meta_data.merchant_config_currency; - let mcc = meta_data.mcc; - let merchant_country_code = meta_data.merchant_country_code; - let merchant_name = meta_data.merchant_name; - let acquirer_bin = meta_data.acquirer_bin; - let acquirer_merchant_id = meta_data.acquirer_merchant_id; - let acquirer_country_code = meta_data.acquirer_country_code; - let three_ds_requestor_name = meta_data.three_ds_requestor_name; - let three_ds_requestor_id = meta_data.three_ds_requestor_id; - let pull_mechanism_for_external_3ds_enabled = - meta_data.pull_mechanism_for_external_3ds_enabled; - let klarna_region = meta_data.klarna_region; - let source_balance_account = meta_data.source_balance_account; - let brand_id = meta_data.brand_id; - let destination_account_number = meta_data.destination_account_number; - - Some(ApiModelMetaData { - google_pay, - apple_pay, - account_name, - merchant_account_id, - terminal_id, - merchant_id, - merchant_config_currency, - apple_pay_combined, - endpoint_prefix, - paypal_sdk, - mcc, - merchant_country_code, - merchant_name, - acquirer_bin, - acquirer_merchant_id, - acquirer_country_code, - three_ds_requestor_name, - three_ds_requestor_id, - pull_mechanism_for_external_3ds_enabled, - klarna_region, - source_balance_account, - brand_id, - destination_account_number, - }) - } - - fn get_custom_gateway_name(connector: Connector) -> String { - match connector { - Connector::Checkout => String::from("checkoutltd"), - Connector::Nuvei => String::from("nuveidigital"), - Connector::Authorizedotnet => String::from("authorizenet"), - Connector::Globalpay => String::from("globalpayments"), - Connector::Bankofamerica | Connector::Cybersource => String::from("cybersource"), - _ => connector.to_string(), - } - } - fn get_google_pay_details( - meta_data: DashboardMetaData, - connector: Connector, - ) -> Option<GoogleApiModelData> { - match meta_data.google_pay { - Some(gpay_data) => { - let google_pay_data = match gpay_data { - GooglePayData::Standard(data) => { - let token_parameter = payments::GpayTokenParameters { - gateway: Self::get_custom_gateway_name(connector), - gateway_merchant_id: data.gateway_merchant_id, - stripe_version: match connector { - Connector::Stripe => Some(String::from("2018-10-31")), - _ => None, - }, - stripe_publishable_key: match connector { - Connector::Stripe => data.stripe_publishable_key, - _ => None, - }, - }; - let merchant_info = payments::GpayMerchantInfo { - merchant_name: data.merchant_name, - merchant_id: data.merchant_id, - }; - let token_specification = payments::GpayTokenizationSpecification { - token_specification_type: String::from("PAYMENT_GATEWAY"), - parameters: token_parameter, - }; - let allowed_payment_methods_parameters = - payments::GpayAllowedMethodsParameters { - allowed_auth_methods: vec![ - "PAN_ONLY".to_string(), - "CRYPTOGRAM_3DS".to_string(), - ], - allowed_card_networks: vec![ - "AMEX".to_string(), - "DISCOVER".to_string(), - "INTERAC".to_string(), - "JCB".to_string(), - "MASTERCARD".to_string(), - "VISA".to_string(), - ], - billing_address_required: None, - billing_address_parameters: None, - assurance_details_required: Some(false), - }; - let allowed_payment_methods = payments::GpayAllowedPaymentMethods { - payment_method_type: String::from("CARD"), - parameters: allowed_payment_methods_parameters, - tokenization_specification: token_specification, - }; - GoogleApiModelData::Standard(payments::GpayMetaData { - merchant_info, - allowed_payment_methods: vec![allowed_payment_methods], - }) - } - GooglePayData::Zen(data) => GoogleApiModelData::Zen(data), - }; - Some(google_pay_data) - } - _ => None, + metadata: request.metadata, } } } diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index d6cdefd79f3..4c41dc7654b 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -230,33 +230,96 @@ api_key="Adyen API Key" key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" -[adyen.metadata] -endpoint_prefix="Live endpoint prefix" -[adyen.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[adyen.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[adyen.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" + +[[adyen.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[adyen.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[adyen.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[adyen.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[adyen.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[adyen.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[adyen.metadata.endpoint_prefix] +name="endpoint_prefix" +label="Live endpoint prefix" +placeholder="Enter Live endpoint prefix" +required=true +type="Text" [adyenplatform_payout] [[adyenplatform_payout.bank_transfer]] payment_method_type = "sepa" -[adyenplatform_payout.metadata] -source_balance_account="Source balance account ID" [adyenplatform_payout.connector_auth.HeaderKey] api_key="Adyen platform's API Key" +[adyenplatform_payout.metadata.source_balance_account] +name="source_balance_account" +label="Source balance account ID" +placeholder="Enter Source balance account ID" +required=true +type="Text" [airwallex] [[airwallex.credit]] @@ -302,6 +365,24 @@ api_key="API Key" key1="Client ID" [airwallex.connector_webhook_details] merchant_secret="Source verification key" +[[airwallex.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[airwallex.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[airwallex.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [authorizedotnet] @@ -350,24 +431,77 @@ merchant_secret="Source verification key" [authorizedotnet.connector_auth.BodyKey] api_key="API Login ID" key1="Transaction Key" -[authorizedotnet.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" -[authorizedotnet.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[authorizedotnet.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" -[authorizedotnet.connector_webhook_details] -merchant_secret="Source verification key" + +[[authorizedotnet.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[authorizedotnet.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[authorizedotnet.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[authorizedotnet.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[authorizedotnet.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[authorizedotnet.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [bambora] [[bambora.credit]] @@ -501,23 +635,76 @@ api_secret="Shared Secret" [bankofamerica.connector_webhook_details] merchant_secret="Source verification key" -[bankofamerica.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[bankofamerica.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - -[bankofamerica.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" +[[bankofamerica.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[bankofamerica.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[bankofamerica.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[bankofamerica.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[bankofamerica.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[bankofamerica.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [bitpay] [[bitpay.crypto]] @@ -574,25 +761,83 @@ key1="Username" [bluesnap.connector_webhook_details] merchant_secret="Source verification key" -[bluesnap.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[bluesnap.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[bluesnap.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" -[bluesnap.metadata] -merchant_id="Merchant Id" +[[bluesnap.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[bluesnap.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[bluesnap.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[bluesnap.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[bluesnap.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[bluesnap.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[bluesnap.metadata.merchant_id] +name="merchant_id" +label="Merchant Id" +placeholder="Enter Merchant Id" +required=false +type="Text" [boku] [[boku.wallet]] @@ -659,9 +904,20 @@ merchant_secret="Source verification key" api_key="Public Key" key1="Merchant Id" api_secret="Private Key" -[braintree.metadata] -merchant_account_id="Merchant Account Id" -merchant_config_currency="Currency" + +[braintree.metadata.merchant_account_id] +name="merchant_account_id" +label="Merchant Account Id" +placeholder="Enter Merchant Account Id" +required=true +type="Text" +[braintree.metadata.merchant_config_currency] +name="merchant_config_currency" +label="Currency" +placeholder="Enter Currency" +required=true +type="Select" +options=[] [cashtocode] [[cashtocode.reward]] @@ -807,28 +1063,95 @@ api_secret="Checkout API Secret Key" [checkout.connector_webhook_details] merchant_secret="Source verification key" -[checkout.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[checkout.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[checkout.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - -[checkout.metadata] -acquirer_bin = "Acquirer Bin" -acquirer_merchant_id = "Acquirer Merchant ID" -acquirer_country_code = "Acquirer Country Code" +[[checkout.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[checkout.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[checkout.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[checkout.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[checkout.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[checkout.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[checkout.metadata.acquirer_bin] +name="acquirer_bin" +label="Acquirer Bin" +placeholder="Enter Acquirer Bin" +required=false +type="Text" +[checkout.metadata.acquirer_merchant_id] +name="acquirer_merchant_id" +label="Acquirer Merchant ID" +placeholder="Enter Acquirer Merchant ID" +required=false +type="Text" +[checkout.metadata.acquirer_country_code] +name="acquirer_country_code" +label="Acquirer Country Code" +placeholder="Enter Acquirer Country Code" +required=false +type="Text" [coinbase] [[coinbase.crypto]] @@ -895,28 +1218,95 @@ api_secret="Shared Secret" [cybersource.connector_webhook_details] merchant_secret="Source verification key" -[cybersource.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[cybersource.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - -[cybersource.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[cybersource.metadata] -acquirer_bin = "Acquirer Bin" -acquirer_merchant_id = "Acquirer Merchant ID" -acquirer_country_code = "Acquirer Country Code" +[[cybersource.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[cybersource.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[cybersource.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[cybersource.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[cybersource.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[cybersource.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[cybersource.metadata.acquirer_bin] +name="acquirer_bin" +label="Acquirer Bin" +placeholder="Enter Acquirer Bin" +required=false +type="Text" +[cybersource.metadata.acquirer_merchant_id] +name="acquirer_merchant_id" +label="Acquirer Merchant ID" +placeholder="Enter Acquirer Merchant ID" +required=false +type="Text" +[cybersource.metadata.acquirer_country_code] +name="acquirer_country_code" +label="Acquirer Country Code" +placeholder="Enter Acquirer Country Code" +required=false +type="Text" [cybersource_payout] [[cybersource_payout.credit]] @@ -1051,8 +1441,14 @@ api_key = "Integration Key" api_key="API Key" key1="Merchant ID" api_secret="API Secret" -[fiserv.metadata] -terminal_id="Terminal ID" + +[fiserv.metadata.terminal_id] +name="terminal_id" +label="Terminal ID" +placeholder="Enter Terminal ID" +required=true +type="Text" + [fiserv.connector_webhook_details] merchant_secret="Source verification key" @@ -1153,14 +1549,34 @@ merchant_secret="Source verification key" [globalpay.connector_auth.BodyKey] api_key="Global App Key" key1="Global App ID" -[globalpay.metadata] -account_name="Account Name" [globalpay.connector_webhook_details] merchant_secret="Source verification key" -[globalpay.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" + +[[globalpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[globalpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[globalpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[globalpay.metadata.account_name] +name="account_name" +label="Account Name" +placeholder="Enter Account Name" +required=true +type="Text" [globepay] [[globepay.wallet]] @@ -1201,17 +1617,31 @@ merchant_secret="Source verification key" [klarna.connector_auth.BodyKey] key1="Klarna Merchant Username" api_key="Klarna Merchant ID Password" -[klarna.metadata] -klarna_region=["Europe","NorthAmerica","Oceania"] +[klarna.metadata.klarna_region] +name="klarna_region" +label="Region of your Klarna Merchant Account" +placeholder="Enter Region of your Klarna Merchant Account" +required=true +type="Select" +options=["Europe","NorthAmerica","Oceania"] [mifinity] [[mifinity.wallet]] payment_method_type = "mifinity" [mifinity.connector_auth.HeaderKey] api_key="key" -[mifinity.metadata] -brand_id="Brand ID" -destination_account_number="Destination Account Number" +[mifinity.metadata.brand_id] +name="brand_id" +label="Merchant Brand ID" +placeholder="Enter Brand ID" +required=true +type="Text" +[mifinity.metadata.destination_account_number] +name="destination_account_number" +label="Destination Account Number" +placeholder="Enter Destination Account Number" +required=true +type="Text" [razorpay] [[razorpay.upi]] @@ -1322,10 +1752,24 @@ merchant_secret="Source verification key" api_key="Enter API Key" [multisafepay.connector_webhook_details] merchant_secret="Source verification key" -[multisafepay.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" +[[multisafepay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[multisafepay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[multisafepay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [nexinets] [[nexinets.credit]] @@ -1381,18 +1825,58 @@ api_key="API Key" key1="Merchant ID" [nexinets.connector_webhook_details] merchant_secret="Source verification key" -[nexinets.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[nexinets.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" + +[[nexinets.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[nexinets.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[nexinets.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] [nmi] [[nmi.credit]] @@ -1443,28 +1927,95 @@ key1="Public Key" [nmi.connector_webhook_details] merchant_secret="Source verification key" -[nmi.metadata] -acquirer_bin = "Acquirer Bin" -acquirer_merchant_id = "Acquirer Merchant ID" -acquirer_country_code = "Acquirer Country Code" - -[nmi.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[nmi.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[nmi.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[nmi.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[nmi.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[nmi.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[nmi.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[nmi.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[nmi.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[nmi.metadata.acquirer_bin] +name="acquirer_bin" +label="Acquirer Bin" +placeholder="Enter Acquirer Bin" +required=false +type="Text" +[nmi.metadata.acquirer_merchant_id] +name="acquirer_merchant_id" +label="Acquirer Merchant ID" +placeholder="Enter Acquirer Merchant ID" +required=false +type="Text" +[nmi.metadata.acquirer_country_code] +name="acquirer_country_code" +label="Acquirer Country Code" +placeholder="Enter Acquirer Country Code" +required=false +type="Text" [noon] [[noon.credit]] @@ -1516,23 +2067,76 @@ api_secret="Application Identifier" [noon.connector_webhook_details] merchant_secret="Source verification key" -[noon.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[noon.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[noon.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[noon.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[noon.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[noon.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[noon.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[noon.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[noon.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [nuvei] [[nuvei.credit]] @@ -1596,23 +2200,76 @@ api_secret="Merchant Secret" [nuvei.connector_webhook_details] merchant_secret="Source verification key" -[nuvei.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[nuvei.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[nuvei.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[nuvei.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[nuvei.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[nuvei.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[nuvei.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[nuvei.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[nuvei.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [opennode] @@ -1789,10 +2446,24 @@ key1="Merchant POS ID" [payu.connector_webhook_details] merchant_secret="Source verification key" -[payu.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" +[[payu.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[payu.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[payu.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [placetopay] [[placetopay.credit]] @@ -1923,18 +2594,57 @@ key1="API Secret" [rapyd.connector_webhook_details] merchant_secret="Source verification key" -[rapyd.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[rapyd.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[rapyd.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[rapyd.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[rapyd.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] [shift4] [[shift4.credit]] @@ -2073,23 +2783,76 @@ api_key="Secret Key" [stripe.connector_webhook_details] merchant_secret="Source verification key" -[stripe.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -stripe_publishable_key="Stripe Publishable Key" -merchant_id="Google Pay Merchant ID" - -[stripe.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[stripe.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[stripe.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[stripe.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[stripe.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[stripe.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[stripe.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[stripe.metadata.google_pay]] +name="stripe:publishableKey" +label="Stripe Publishable Key" +placeholder="Enter Stripe Publishable Key" +required=true +type="Text" [stax] [[stax.credit]] @@ -2236,18 +2999,77 @@ api_secret="Secret Key" [trustpay.connector_webhook_details] merchant_secret="Source verification key" -[trustpay.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[trustpay.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[trustpay.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[trustpay.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[trustpay.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[trustpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[trustpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[trustpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + [tsys] [[tsys.credit]] @@ -2399,23 +3221,76 @@ key1="Password" [worldpay.connector_webhook_details] merchant_secret="Source verification key" -[worldpay.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[worldpay.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[worldpay.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[worldpay.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[worldpay.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[worldpay.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[worldpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[worldpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[worldpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [zen] [[zen.credit]] @@ -2477,12 +3352,32 @@ api_key="API Key" [zen.connector_webhook_details] merchant_secret="Source verification key" -[zen.metadata.apple_pay] -terminal_uuid="Terminal UUID" -pay_wall_secret="Pay Wall Secret" -[zen.metadata.google_pay] -terminal_uuid="Terminal UUID" -pay_wall_secret="Pay Wall Secret" + +[[zen.metadata.apple_pay]] +name="terminal_uuid" +label="Terminal UUID" +placeholder="Enter Terminal UUID" +required=true +type="Text" +[[zen.metadata.apple_pay]] +name="pay_wall_secret" +label="Pay Wall Secret" +placeholder="Enter Pay Wall Secret" +required=true +type="Text" + +[[zen.metadata.google_pay]] +name="terminal_uuid" +label="Terminal UUID" +placeholder="Enter Terminal UUID" +required=true +type="Text" +[[zen.metadata.google_pay]] +name="pay_wall_secret" +label="Pay Wall Secret" +placeholder="Enter Pay Wall Secret" +required=true +type="Text" [zsl] [[zsl.bank_transfer]] @@ -2709,8 +3604,14 @@ api_key="Api Key" payment_method_type = "sepa" [[adyen_payout.wallet]] payment_method_type = "paypal" -[adyen_payout.metadata] - endpoint_prefix="Live endpoint prefix" + +[adyen_payout.metadata.endpoint_prefix] +name="endpoint_prefix" +label="Live endpoint prefix" +placeholder="Enter Live endpoint prefix" +required=true +type="Text" + [adyen_payout.connector_auth.SignatureKey] api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" @@ -2736,23 +3637,75 @@ key1 = "Wise Account Id" [threedsecureio] [threedsecureio.connector_auth.HeaderKey] api_key="Api Key" -[threedsecureio.metadata] -mcc="MCC" -merchant_country_code="3 digit numeric country code" -merchant_name="Name of the merchant" -pull_mechanism_for_external_3ds_enabled=true + +[threedsecureio.metadata.mcc] +name="mcc" +label="MCC" +placeholder="Enter MCC" +required=true +type="Text" +[threedsecureio.metadata.merchant_country_code] +name="merchant_country_code" +label="3 digit numeric country code" +placeholder="Enter 3 digit numeric country code" +required=true +type="Text" +[threedsecureio.metadata.merchant_name] +name="merchant_name" +label="Name of the merchant" +placeholder="Enter Name of the merchant" +required=true +type="Text" +[threedsecureio.metadata.pull_mechanism_for_external_3ds_enabled] +name="pull_mechanism_for_external_3ds_enabled" +label="Pull Mechanism Enabled" +placeholder="Enter Pull Mechanism Enabled" +required=false +type="Toggle" + + [netcetera] [netcetera.connector_auth.CertificateAuth] certificate="Base64 encoded PEM formatted certificate chain" private_key="Base64 encoded PEM formatted private key" -[netcetera.metadata] -mcc="MCC" -merchant_country_code="3 digit numeric country code" -merchant_name="Name of the merchant" -endpoint_prefix="string that will replace '{prefix}' in this base url 'https://{prefix}.3ds-server.prev.netcetera-cloud-payment.ch'" -three_ds_requestor_name="ThreeDS requestor name" -three_ds_requestor_id="ThreeDS request id" + +[netcetera.metadata.mcc] +name="mcc" +label="MCC" +placeholder="Enter MCC" +required=true +type="Text" +[netcetera.metadata.endpoint_prefix] +name="endpoint_prefix" +label="Live endpoint prefix" +placeholder="string that will replace '{prefix}' in this base url 'https://{prefix}.3ds-server.prev.netcetera-cloud-payment.ch'" +required=true +type="Text" +[netcetera.metadata.merchant_country_code] +name="merchant_country_code" +label="3 digit numeric country code" +placeholder="Enter 3 digit numeric country code" +required=true +type="Text" +[netcetera.metadata.merchant_name] +name="merchant_name" +label="Name of the merchant" +placeholder="Enter Name of the merchant" +required=true +type="Text" +[netcetera.metadata.three_ds_requestor_name] +name="three_ds_requestor_name" +label="ThreeDS requestor name" +placeholder="Enter ThreeDS requestor name" +required=true +type="Text" +[netcetera.metadata.three_ds_requestor_id] +name="three_ds_requestor_id" +label="ThreeDS request id" +placeholder="Enter ThreeDS request id" +required=true +type="Text" [billwerk] [[billwerk.credit]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index c31b75ad3fc..7f4772a0b1b 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -124,27 +124,76 @@ key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" -[adyen.metadata] -endpoint_prefix="Live endpoint prefix" - -[adyen.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[adyen.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[adyen.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - +[[adyen.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[adyen.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[adyen.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[adyen.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" + +[adyen.metadata.endpoint_prefix] +name="endpoint_prefix" +label="Live endpoint prefix" +placeholder="Enter Live endpoint prefix" +required=true +type="Text" [airwallex] @@ -238,24 +287,76 @@ body_type="BodyKey" [authorizedotnet.connector_auth.BodyKey] api_key="API Login ID" key1="Transaction Key" -[authorizedotnet.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" -[authorizedotnet.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[authorizedotnet.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" -[authorizedotnet.connector_webhook_details] -merchant_secret="Source verification key" + +[[authorizedotnet.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[authorizedotnet.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[authorizedotnet.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[authorizedotnet.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[authorizedotnet.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [bitpay] [[bitpay.crypto]] @@ -312,25 +413,82 @@ key1="Username" [bluesnap.connector_webhook_details] merchant_secret="Source verification key" -[bluesnap.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[bluesnap.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[bluesnap.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" -[bluesnap.metadata] -merchant_id="Merchant Id" +[[bluesnap.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[bluesnap.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[bluesnap.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[bluesnap.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[bluesnap.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[bluesnap.metadata.merchant_id] +name="merchant_id" +label="Merchant Id" +placeholder="Enter Merchant Id" +required=false +type="Text" [braintree] [[braintree.credit]] @@ -378,9 +536,20 @@ key1="Merchant Id" api_secret="Private Key" [braintree.connector_webhook_details] merchant_secret="Source verification key" -[braintree.metadata] -merchant_account_id="Merchant Account Id" -merchant_config_currency="Currency" + +[braintree.metadata.merchant_account_id] +name="merchant_account_id" +label="Merchant Account Id" +placeholder="Enter Merchant Account Id" +required=true +type="Text" +[braintree.metadata.merchant_config_currency] +name="merchant_config_currency" +label="Currency" +placeholder="Enter Currency" +required=true +type="Select" +options=[] [bambora] [[bambora.credit]] @@ -514,23 +683,75 @@ api_secret="Shared Secret" [bankofamerica.connector_webhook_details] merchant_secret="Source verification key" -[bankofamerica.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[bankofamerica.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - -[bankofamerica.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" +[[bankofamerica.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[bankofamerica.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[bankofamerica.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[bankofamerica.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[bankofamerica.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [cashtocode] [[cashtocode.reward]] @@ -685,24 +906,75 @@ api_secret="Checkout API Secret Key" [checkout.connector_webhook_details] merchant_secret="Source verification key" -[checkout.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[checkout.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[checkout.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - +[[checkout.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[checkout.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[checkout.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[checkout.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[checkout.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [coinbase] @@ -761,23 +1033,75 @@ api_secret="Shared Secret" [cybersource.connector_webhook_details] merchant_secret="Source verification key" -[cybersource.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[cybersource.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - -[cybersource.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" +[[cybersource.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[cybersource.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[cybersource.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[cybersource.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[cybersource.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [dlocal] [[dlocal.credit]] @@ -867,8 +1191,13 @@ key1="Merchant ID" api_secret="API Secret" [fiserv.connector_webhook_details] merchant_secret="Source verification key" -[fiserv.metadata] -terminal_id="Terminal ID" + +[fiserv.metadata.terminal_id] +name="terminal_id" +label="Terminal ID" +placeholder="Enter Terminal ID" +required=true +type="Text" [forte] [[forte.credit]] @@ -970,12 +1299,32 @@ api_key="Global App Key" key1="Global App ID" [globalpay.connector_webhook_details] merchant_secret="Source verification key" -[globalpay.metadata] -account_name="Account Name" -[globalpay.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" + +[[globalpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[globalpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[globalpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[globalpay.metadata.account_name] +name="account_name" +label="Account Name" +placeholder="Enter Account Name" +required=true +type="Text" [globepay] @@ -1005,17 +1354,31 @@ merchant_secret="Source verification key" [klarna.connector_auth.BodyKey] key1="Klarna Merchant Username" api_key="Klarna Merchant ID Password" -[klarna.metadata] -klarna_region=["Europe","NorthAmerica","Oceania"] +[klarna.metadata.klarna_region] +name="klarna_region" +label="Region of your Klarna Merchant Account" +placeholder="Enter Region of your Klarna Merchant Account" +required=true +type="Select" +options=["Europe","NorthAmerica","Oceania"] [mifinity] [[mifinity.wallet]] payment_method_type = "mifinity" [mifinity.connector_auth.HeaderKey] api_key="key" -[mifinity.metadata] -brand_id="Brand ID" -destination_account_number="Destination Account Number" +[mifinity.metadata.brand_id] +name="brand_id" +label="Merchant Brand ID" +placeholder="Enter Brand ID" +required=true +type="Text" +[mifinity.metadata.destination_account_number] +name="destination_account_number" +label="Destination Account Number" +placeholder="Enter Destination Account Number" +required=true +type="Text" [razorpay] [[razorpay.upi]] @@ -1172,20 +1535,57 @@ merchant_secret="Source verification key" [nexinets.connector_auth.BodyKey] api_key="API Key" key1="Merchant ID" -[nexinets.connector_webhook_details] -merchant_secret="Source verification key" -[nexinets.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[nexinets.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" + +[[nexinets.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[nexinets.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] [nmi] [[nmi.credit]] @@ -1382,10 +1782,24 @@ key1="Merchant POS ID" [payu.connector_webhook_details] merchant_secret="Source verification key" -[payu.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" +[[payu.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[payu.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[payu.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [rapyd] [[rapyd.credit]] @@ -1432,18 +1846,56 @@ key1="API Secret" [rapyd.connector_webhook_details] merchant_secret="Source verification key" -[rapyd.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[rapyd.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[rapyd.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[rapyd.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] [shift4] [[shift4.credit]] @@ -1567,22 +2019,76 @@ is_verifiable = true api_key="Secret Key" [stripe.connector_webhook_details] merchant_secret="Source verification key" -[stripe.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -stripe_publishable_key="Stripe Publishable Key" -merchant_id="Google Pay Merchant ID" -[stripe.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[stripe.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" + +[[stripe.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[stripe.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[stripe.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[stripe.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[stripe.metadata.google_pay]] +name="stripe:publishableKey" +label="Stripe Publishable Key" +placeholder="Enter Stripe Publishable Key" +required=true +type="Text" @@ -1644,18 +2150,76 @@ key1="Project ID" api_secret="Secret Key" [trustpay.connector_webhook_details] merchant_secret="Source verification key" -[trustpay.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[trustpay.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" + +[[trustpay.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[trustpay.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[trustpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[trustpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[trustpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [worldline] [[worldline.credit]] @@ -1749,25 +2313,76 @@ merchant_secret="Source verification key" [worldpay.connector_auth.BodyKey] api_key="Username" key1="Password" -[worldpay.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" -[worldpay.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[worldpay.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" -[worldpay.connector_webhook_details] -merchant_secret="Source verification key" +[[worldpay.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[worldpay.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[worldpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[worldpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[worldpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [payme] @@ -1976,9 +2591,32 @@ merchant_secret="Source verification key" [zen.metadata.apple_pay] terminal_uuid="Terminal UUID" pay_wall_secret="Pay Wall Secret" -[zen.metadata.google_pay] -terminal_uuid="Terminal UUID" -pay_wall_secret="Pay Wall Secret" + +[[zen.metadata.apple_pay]] +name="terminal_uuid" +label="Terminal UUID" +placeholder="Enter Terminal UUID" +required=true +type="Text" +[[zen.metadata.apple_pay]] +name="pay_wall_secret" +label="Pay Wall Secret" +placeholder="Enter Pay Wall Secret" +required=true +type="Text" + +[[zen.metadata.google_pay]] +name="terminal_uuid" +label="Terminal UUID" +placeholder="Enter Terminal UUID" +required=true +type="Text" +[[zen.metadata.google_pay]] +name="pay_wall_secret" +label="Pay Wall Secret" +placeholder="Enter Pay Wall Secret" +required=true +type="Text" [zsl] [[zsl.bank_transfer]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 664309c9921..18eaa8da7b4 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -230,34 +230,97 @@ api_key="Adyen API Key" key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" -[adyen.metadata] -endpoint_prefix="Live endpoint prefix" -[adyen.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[adyen.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[adyen.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" + +[[adyen.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[adyen.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[adyen.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[adyen.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[adyen.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[adyen.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[adyen.metadata.endpoint_prefix] +name="endpoint_prefix" +label="Live endpoint prefix" +placeholder="Enter Live endpoint prefix" +required=true +type="Text" [adyenplatform_payout] [[adyenplatform_payout.bank_transfer]] payment_method_type = "sepa" -[adyenplatform_payout.metadata] - source_balance_account = "Source balance account ID" [adyenplatform_payout.connector_auth.HeaderKey] api_key = "Adyen platform's API Key" +[adyenplatform_payout.metadata.source_balance_account] +name="source_balance_account" +label="Source balance account ID" +placeholder="Enter Source balance account ID" +required=true +type="Text" + [airwallex] [[airwallex.credit]] payment_method_type = "Mastercard" @@ -303,6 +366,27 @@ key1="Client ID" [airwallex.connector_webhook_details] merchant_secret="Source verification key" +[airwallex.connector_webhook_details] +merchant_secret="Source verification key" +[[airwallex.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[airwallex.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[airwallex.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + [authorizedotnet] [[authorizedotnet.credit]] @@ -350,25 +434,79 @@ merchant_secret="Source verification key" [authorizedotnet.connector_auth.BodyKey] api_key="API Login ID" key1="Transaction Key" -[authorizedotnet.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" -[authorizedotnet.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[authorizedotnet.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" [authorizedotnet.connector_webhook_details] merchant_secret="Source verification key" +[[authorizedotnet.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[authorizedotnet.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[authorizedotnet.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[authorizedotnet.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[authorizedotnet.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[authorizedotnet.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + [bambora] [[bambora.credit]] payment_method_type = "Mastercard" @@ -500,23 +638,75 @@ api_secret="Shared Secret" [bankofamerica.connector_webhook_details] merchant_secret="Source verification key" -[bankofamerica.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[bankofamerica.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - -[bankofamerica.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" +[[bankofamerica.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[bankofamerica.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[bankofamerica.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[bankofamerica.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[bankofamerica.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[bankofamerica.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [bitpay] [[bitpay.crypto]] @@ -573,25 +763,83 @@ key1="Username" [bluesnap.connector_webhook_details] merchant_secret="Source verification key" -[bluesnap.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[bluesnap.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[bluesnap.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" -[bluesnap.metadata] -merchant_id="Merchant Id" +[[bluesnap.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[bluesnap.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[bluesnap.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[bluesnap.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[bluesnap.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[bluesnap.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[bluesnap.metadata.merchant_id] +name="merchant_id" +label="Merchant Id" +placeholder="Enter Merchant Id" +required=false +type="Text" + [boku] [[boku.wallet]] @@ -658,9 +906,19 @@ merchant_secret="Source verification key" api_key="Public Key" key1="Merchant Id" api_secret="Private Key" -[braintree.metadata] -merchant_account_id="Merchant Account Id" -merchant_config_currency="Currency" +[braintree.metadata.merchant_account_id] +name="merchant_account_id" +label="Merchant Account Id" +placeholder="Enter Merchant Account Id" +required=true +type="Text" +[braintree.metadata.merchant_config_currency] +name="merchant_config_currency" +label="Currency" +placeholder="Enter Currency" +required=true +type="Select" +options=[] [cashtocode] [[cashtocode.reward]] @@ -806,28 +1064,94 @@ api_secret="Checkout API Secret Key" [checkout.connector_webhook_details] merchant_secret="Source verification key" -[checkout.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[checkout.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[checkout.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - -[checkout.metadata] -acquirer_bin = "Acquirer Bin" -acquirer_merchant_id = "Acquirer Merchant ID" -acquirer_country_code = "Acquirer Country Code" +[[checkout.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[checkout.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[checkout.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[checkout.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[checkout.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[checkout.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[checkout.metadata.acquirer_bin] +name="acquirer_bin" +label="Acquirer Bin" +placeholder="Enter Acquirer Bin" +required=false +type="Text" +[checkout.metadata.acquirer_merchant_id] +name="acquirer_merchant_id" +label="Acquirer Merchant ID" +placeholder="Enter Acquirer Merchant ID" +required=false +type="Text" +[checkout.metadata.acquirer_country_code] +name="acquirer_country_code" +label="Acquirer Country Code" +placeholder="Enter Acquirer Country Code" +required=false +type="Text" [coinbase] [[coinbase.crypto]] @@ -894,28 +1218,94 @@ api_secret="Shared Secret" [cybersource.connector_webhook_details] merchant_secret="Source verification key" -[cybersource.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[cybersource.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" - -[cybersource.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[cybersource.metadata] -acquirer_bin = "Acquirer Bin" -acquirer_merchant_id = "Acquirer Merchant ID" -acquirer_country_code = "Acquirer Country Code" +[[cybersource.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[cybersource.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[cybersource.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[cybersource.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[cybersource.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[cybersource.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[cybersource.metadata.acquirer_bin] +name="acquirer_bin" +label="Acquirer Bin" +placeholder="Enter Acquirer Bin" +required=false +type="Text" +[cybersource.metadata.acquirer_merchant_id] +name="acquirer_merchant_id" +label="Acquirer Merchant ID" +placeholder="Enter Acquirer Merchant ID" +required=false +type="Text" +[cybersource.metadata.acquirer_country_code] +name="acquirer_country_code" +label="Acquirer Country Code" +placeholder="Enter Acquirer Country Code" +required=false +type="Text" [cybersource_payout] [[cybersource_payout.credit]] @@ -1050,11 +1440,16 @@ api_key = "Integration Key" api_key="API Key" key1="Merchant ID" api_secret="API Secret" -[fiserv.metadata] -terminal_id="Terminal ID" [fiserv.connector_webhook_details] merchant_secret="Source verification key" +[fiserv.metadata.terminal_id] +name="terminal_id" +label="Terminal ID" +placeholder="Enter Terminal ID" +required=true +type="Text" + [forte] [[forte.credit]] payment_method_type = "Mastercard" @@ -1152,14 +1547,34 @@ merchant_secret="Source verification key" [globalpay.connector_auth.BodyKey] api_key="Global App Key" key1="Global App ID" -[globalpay.metadata] -account_name="Account Name" [globalpay.connector_webhook_details] merchant_secret="Source verification key" -[globalpay.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" + +[[globalpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[globalpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[globalpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[globalpay.metadata.account_name] +name="account_name" +label="Account Name" +placeholder="Enter Account Name" +required=true +type="Text" [globepay] [[globepay.wallet]] @@ -1200,17 +1615,31 @@ merchant_secret="Source verification key" [klarna.connector_auth.BodyKey] key1="Klarna Merchant Username" api_key="Klarna Merchant ID Password" -[klarna.metadata] -klarna_region=["Europe","NorthAmerica","Oceania"] +[klarna.metadata.klarna_region] +name="klarna_region" +label="Region of your Klarna Merchant Account" +placeholder="Enter Region of your Klarna Merchant Account" +required=true +type="Select" +options=["Europe","NorthAmerica","Oceania"] [mifinity] [[mifinity.wallet]] payment_method_type = "mifinity" [mifinity.connector_auth.HeaderKey] api_key="key" -[mifinity.metadata] -brand_id="Brand ID" -destination_account_number="Destination Account Number" +[mifinity.metadata.brand_id] +name="brand_id" +label="Merchant Brand ID" +placeholder="Enter Brand ID" +required=true +type="Text" +[mifinity.metadata.destination_account_number] +name="destination_account_number" +label="Destination Account Number" +placeholder="Enter Destination Account Number" +required=true +type="Text" [razorpay] [[razorpay.upi]] @@ -1321,10 +1750,25 @@ merchant_secret="Source verification key" api_key="Enter API Key" [multisafepay.connector_webhook_details] merchant_secret="Source verification key" -[multisafepay.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" + +[[multisafepay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[multisafepay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[multisafepay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [nexinets] [[nexinets.credit]] @@ -1380,18 +1824,57 @@ api_key="API Key" key1="Merchant ID" [nexinets.connector_webhook_details] merchant_secret="Source verification key" -[nexinets.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[nexinets.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" + +[[nexinets.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[nexinets.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[nexinets.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] [nmi] [[nmi.credit]] @@ -1442,28 +1925,94 @@ key1="Public Key" [nmi.connector_webhook_details] merchant_secret="Source verification key" -[nmi.metadata] -acquirer_bin = "Acquirer Bin" -acquirer_merchant_id = "Acquirer Merchant ID" -acquirer_country_code = "Acquirer Country Code" - -[nmi.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[nmi.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[nmi.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[nmi.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[nmi.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[nmi.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[nmi.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[nmi.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[nmi.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" + +[nmi.metadata.acquirer_bin] +name="acquirer_bin" +label="Acquirer Bin" +placeholder="Enter Acquirer Bin" +required=false +type="Text" +[nmi.metadata.acquirer_merchant_id] +name="acquirer_merchant_id" +label="Acquirer Merchant ID" +placeholder="Enter Acquirer Merchant ID" +required=false +type="Text" +[nmi.metadata.acquirer_country_code] +name="acquirer_country_code" +label="Acquirer Country Code" +placeholder="Enter Acquirer Country Code" +required=false +type="Text" [noon] [[noon.credit]] @@ -1515,23 +2064,75 @@ api_secret="Application Identifier" [noon.connector_webhook_details] merchant_secret="Source verification key" -[noon.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[noon.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[noon.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[noon.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[noon.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[noon.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[noon.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[noon.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[noon.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [nuvei] [[nuvei.credit]] @@ -1595,23 +2196,75 @@ api_secret="Merchant Secret" [nuvei.connector_webhook_details] merchant_secret="Source verification key" -[nuvei.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[nuvei.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[nuvei.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[nuvei.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[nuvei.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[nuvei.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[nuvei.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[nuvei.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[nuvei.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [opennode] @@ -1788,10 +2441,24 @@ key1="Merchant POS ID" [payu.connector_webhook_details] merchant_secret="Source verification key" -[payu.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" +[[payu.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[payu.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[payu.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [placetopay] [[placetopay.credit]] @@ -1922,18 +2589,56 @@ key1="API Secret" [rapyd.connector_webhook_details] merchant_secret="Source verification key" -[rapyd.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[rapyd.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[rapyd.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[rapyd.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[rapyd.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] [shift4] [[shift4.credit]] @@ -2072,23 +2777,75 @@ api_key="Secret Key" [stripe.connector_webhook_details] merchant_secret="Source verification key" -[stripe.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -stripe_publishable_key="Stripe Publishable Key" -merchant_id="Google Pay Merchant ID" - -[stripe.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[stripe.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[stripe.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[stripe.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[stripe.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[stripe.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[stripe.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[stripe.metadata.google_pay]] +name="stripe:publishableKey" +label="Stripe Publishable Key" +placeholder="Enter Stripe Publishable Key" +required=true +type="Text" [stax] [[stax.credit]] @@ -2235,18 +2992,75 @@ api_secret="Secret Key" [trustpay.connector_webhook_details] merchant_secret="Source verification key" -[trustpay.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[trustpay.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[trustpay.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[trustpay.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[trustpay.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[trustpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[trustpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[trustpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [tsys] [[tsys.credit]] @@ -2398,23 +3212,75 @@ key1="Password" [worldpay.connector_webhook_details] merchant_secret="Source verification key" -[worldpay.metadata.google_pay] -merchant_name="Google Pay Merchant Name" -gateway_merchant_id="Google Pay Merchant Key" -merchant_id="Google Pay Merchant ID" - -[worldpay.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="web" -initiative_context="Domain Name" -payment_processing_details_at="Connector" -[worldpay.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" +[[worldpay.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[worldpay.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[worldpay.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + +[[worldpay.metadata.google_pay]] +name="merchant_name" +label="Google Pay Merchant Name" +placeholder="Enter Google Pay Merchant Name" +required=true +type="Text" +[[worldpay.metadata.google_pay]] +name="merchant_id" +label="Google Pay Merchant Id" +placeholder="Enter Google Pay Merchant Id" +required=true +type="Text" +[[worldpay.metadata.google_pay]] +name="gateway_merchant_id" +label="Google Pay Merchant Key" +placeholder="Enter Google Pay Merchant Key" +required=true +type="Text" [zen] [[zen.credit]] @@ -2476,12 +3342,31 @@ api_key="API Key" [zen.connector_webhook_details] merchant_secret="Source verification key" -[zen.metadata.apple_pay] -terminal_uuid="Terminal UUID" -pay_wall_secret="Pay Wall Secret" -[zen.metadata.google_pay] -terminal_uuid="Terminal UUID" -pay_wall_secret="Pay Wall Secret" +[[zen.metadata.apple_pay]] +name="terminal_uuid" +label="Terminal UUID" +placeholder="Enter Terminal UUID" +required=true +type="Text" +[[zen.metadata.apple_pay]] +name="pay_wall_secret" +label="Pay Wall Secret" +placeholder="Enter Pay Wall Secret" +required=true +type="Text" + +[[zen.metadata.google_pay]] +name="terminal_uuid" +label="Terminal UUID" +placeholder="Enter Terminal UUID" +required=true +type="Text" +[[zen.metadata.google_pay]] +name="pay_wall_secret" +label="Pay Wall Secret" +placeholder="Enter Pay Wall Secret" +required=true +type="Text" [zsl] [[zsl.bank_transfer]] @@ -2710,13 +3595,18 @@ api_key="Api Key" payment_method_type = "sepa" [[adyen_payout.wallet]] payment_method_type = "paypal" -[adyen_payout.metadata] - endpoint_prefix="Live endpoint prefix" [adyen_payout.connector_auth.SignatureKey] api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" key1 = "Adyen Account Id" +[adyen_payout.metadata.endpoint_prefix] +name="endpoint_prefix" +label="Live endpoint prefix" +placeholder="Enter Live endpoint prefix" +required=true +type="Text" + [stripe_payout] [[stripe_payout.bank_transfer]] payment_method_type = "ach" @@ -2737,24 +3627,79 @@ key1 = "Wise Account Id" [threedsecureio] [threedsecureio.connector_auth.HeaderKey] api_key="Api Key" -[threedsecureio.metadata] -mcc="MCC" -merchant_country_code="3 digit numeric country code" -merchant_name="Name of the merchant" -pull_mechanism_for_external_3ds_enabled=true + +[threedsecureio.metadata.mcc] +name="mcc" +label="MCC" +placeholder="Enter MCC" +required=true +type="Text" +[threedsecureio.metadata.merchant_country_code] +name="merchant_country_code" +label="3 digit numeric country code" +placeholder="Enter 3 digit numeric country code" +required=true +type="Text" +[threedsecureio.metadata.merchant_name] +name="merchant_name" +label="Name of the merchant" +placeholder="Enter Name of the merchant" +required=true +type="Text" +[threedsecureio.metadata.pull_mechanism_for_external_3ds_enabled] +name="pull_mechanism_for_external_3ds_enabled" +label="Pull Mechanism Enabled" +placeholder="Enter Pull Mechanism Enabled" +required=false +type="Toggle" [netcetera] [netcetera.connector_auth.CertificateAuth] certificate="Base64 encoded PEM formatted certificate chain" private_key="Base64 encoded PEM formatted private key" [netcetera.metadata] -mcc="MCC" merchant_country_code="3 digit numeric country code" merchant_name="Name of the merchant" -endpoint_prefix="string that will replace '{prefix}' in this base url 'https://{prefix}.3ds-server.prev.netcetera-cloud-payment.ch'" three_ds_requestor_name="ThreeDS requestor name" three_ds_requestor_id="ThreeDS request id" +[netcetera.metadata.endpoint_prefix] +name="endpoint_prefix" +label="Live endpoint prefix" +placeholder="string that will replace '{prefix}' in this base url 'https://{prefix}.3ds-server.prev.netcetera-cloud-payment.ch'" +required=true +type="Text" +[netcetera.metadata.mcc] +name="mcc" +label="MCC" +placeholder="Enter MCC" +required=true +type="Text" +[netcetera.metadata.merchant_country_code] +name="merchant_country_code" +label="3 digit numeric country code" +placeholder="Enter 3 digit numeric country code" +required=true +type="Text" +[netcetera.metadata.merchant_name] +name="merchant_name" +label="Name of the merchant" +placeholder="Enter Name of the merchant" +required=true +type="Text" +[netcetera.metadata.three_ds_requestor_name] +name="three_ds_requestor_name" +label="ThreeDS requestor name" +placeholder="Enter ThreeDS requestor name" +required=true +type="Text" +[netcetera.metadata.three_ds_requestor_id] +name="three_ds_requestor_id" +label="ThreeDS request id" +placeholder="Enter ThreeDS request id" +required=true +type="Text" + [billwerk] [[billwerk.credit]] payment_method_type = "Mastercard"
2024-06-22T14:29:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> **Dashboard Changes** https://github.com/juspay/hyperswitch-control-center/pull/854 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d65d7b5ccaf3ba0d53a83e1f483a04fc409584c3
juspay/hyperswitch
juspay__hyperswitch-5066
Bug: Collect billing details from wallet connector based on the `collect_billing_details_from_wallet_connector` field We were always passing in some parameters in the wallet session token in order to collect the billing details form the wallet connectors (like google pay and apple pay) always. Instead of collecting it always this we should add a field (`collect_billing_details_from_wallet_connector`) in the business profile which if set to `true` we should add some fields in the session token to collect the shipping details from the wallet connectors. Reference: https://github.com/juspay/hyperswitch/pull/4601
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 81761fac70d..58e11c4d0d4 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -950,9 +950,14 @@ pub struct BusinessProfileCreate { /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, - /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments + /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, + /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] + pub collect_billing_details_from_wallet_connector: Option<bool>, + /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. @@ -1038,9 +1043,14 @@ pub struct BusinessProfileResponse { /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, - /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments + /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, + /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] + pub collect_billing_details_from_wallet_connector: Option<bool>, + /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. @@ -1118,9 +1128,14 @@ pub struct BusinessProfileUpdate { // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, - /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments + /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, + /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] + pub collect_billing_details_from_wallet_connector: Option<bool>, + /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index cd36c53a12b..d8321524a1e 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4135,6 +4135,7 @@ pub struct GpayAllowedMethodsParameters { /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required + #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index b956140a65e..48eedc6110c 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -41,6 +41,7 @@ pub struct BusinessProfile { pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, + pub collect_billing_details_from_wallet_connector: Option<bool>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -73,6 +74,7 @@ pub struct BusinessProfileNew { pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, + pub collect_billing_details_from_wallet_connector: Option<bool>, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -102,6 +104,7 @@ pub struct BusinessProfileUpdateInternal { pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, + pub collect_billing_details_from_wallet_connector: Option<bool>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -128,6 +131,7 @@ pub enum BusinessProfileUpdate { extended_card_info_config: Option<pii::SecretSerdeValue>, use_billing_as_payment_method_billing: Option<bool>, collect_shipping_details_from_wallet_connector: Option<bool>, + collect_billing_details_from_wallet_connector: Option<bool>, is_connector_agnostic_mit_enabled: Option<bool>, }, ExtendedCardInfoUpdate { @@ -163,6 +167,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { extended_card_info_config, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled, } => Self { profile_name, @@ -186,6 +191,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { extended_card_info_config, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled, ..Default::default() }, @@ -235,6 +241,8 @@ impl From<BusinessProfileNew> for BusinessProfile { use_billing_as_payment_method_billing: new.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: new .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: new + .collect_billing_details_from_wallet_connector, } } } @@ -265,6 +273,7 @@ impl BusinessProfileUpdate { is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, } = self.into(); BusinessProfile { profile_name: profile_name.unwrap_or(source.profile_name), @@ -292,6 +301,7 @@ impl BusinessProfileUpdate { extended_card_info_config, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, ..source } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6149af1f505..98f1b2fbbec 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -203,6 +203,7 @@ diesel::table! { is_connector_agnostic_mit_enabled -> Nullable<Bool>, use_billing_as_payment_method_billing -> Nullable<Bool>, collect_shipping_details_from_wallet_connector -> Nullable<Bool>, + collect_billing_details_from_wallet_connector -> Nullable<Bool>, } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 7d69b7f9971..b86fed02f32 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -456,6 +456,7 @@ pub async fn update_business_profile_cascade( extended_card_info_config: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, is_connector_agnostic_mit_enabled: None, }; @@ -1723,6 +1724,8 @@ pub async fn update_business_profile( use_billing_as_payment_method_billing: request.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: request .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: request + .collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled, }; diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 1223d861ebd..43900ac2b64 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -295,23 +295,29 @@ async fn create_applepay_session_token( router_data.request.to_owned(), )?; - let billing_variants = enums::FieldType::get_billing_variants(); - - let required_billing_contact_fields = is_dynamic_fields_required( - &state.conf.required_fields, - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::ApplePay, - &connector.connector_name, - billing_variants, - ) - .then_some(payment_types::ApplePayBillingContactFields(vec![ - payment_types::ApplePayAddressParameters::PostalAddress, - ])); + let required_billing_contact_fields = business_profile + .collect_billing_details_from_wallet_connector + .unwrap_or(false) + .then_some({ + let billing_variants = enums::FieldType::get_billing_variants(); + is_dynamic_fields_required( + &state.conf.required_fields, + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + &connector.connector_name, + billing_variants, + ) + .then_some(payment_types::ApplePayBillingContactFields(vec![ + payment_types::ApplePayAddressParameters::PostalAddress, + ])) + }) + .flatten(); - let required_shipping_contact_fields = - if business_profile.collect_shipping_details_from_wallet_connector == Some(true) { + let required_shipping_contact_fields = business_profile + .collect_shipping_details_from_wallet_connector + .unwrap_or(false) + .then_some({ let shipping_variants = enums::FieldType::get_shipping_variants(); - is_dynamic_fields_required( &state.conf.required_fields, enums::PaymentMethod::Wallet, @@ -324,9 +330,8 @@ async fn create_applepay_session_token( payment_types::ApplePayAddressParameters::Phone, payment_types::ApplePayAddressParameters::Email, ])) - } else { - None - }; + }) + .flatten(); // Get apple pay payment request let applepay_payment_request = get_apple_pay_payment_request( @@ -562,15 +567,20 @@ fn create_gpay_session_token( expected_format: "gpay_metadata_format".to_string(), })?; - let billing_variants = enums::FieldType::get_billing_variants(); + let is_billing_details_required = + if business_profile.collect_billing_details_from_wallet_connector == Some(true) { + let billing_variants = enums::FieldType::get_billing_variants(); - let is_billing_details_required = is_dynamic_fields_required( - &state.conf.required_fields, - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::GooglePay, - &connector.connector_name, - billing_variants, - ); + is_dynamic_fields_required( + &state.conf.required_fields, + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + &connector.connector_name, + billing_variants, + ) + } else { + false + }; let billing_address_parameters = is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters { diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index caa976580b8..b9f5da13cf4 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -285,6 +285,7 @@ pub async fn update_business_profile_active_algorithm_ref( extended_card_info_config: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, is_connector_agnostic_mit_enabled: None, }; diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 77693157f62..36c3ba96210 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -99,6 +99,8 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf .transpose()?, collect_shipping_details_from_wallet_connector: item .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: item + .collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, }) } @@ -211,7 +213,11 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)> .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: request - .collect_shipping_details_from_wallet_connector, + .collect_shipping_details_from_wallet_connector + .or(Some(false)), + collect_billing_details_from_wallet_connector: request + .collect_billing_details_from_wallet_connector + .or(Some(false)), }) } } diff --git a/migrations/2024-06-20-142013_collect_billing_details_from_wallet_connector/down.sql b/migrations/2024-06-20-142013_collect_billing_details_from_wallet_connector/down.sql new file mode 100644 index 00000000000..417bdac8b5a --- /dev/null +++ b/migrations/2024-06-20-142013_collect_billing_details_from_wallet_connector/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +ALTER TABLE business_profile DROP COLUMN IF EXISTS collect_billing_details_from_wallet_connector; \ No newline at end of file diff --git a/migrations/2024-06-20-142013_collect_billing_details_from_wallet_connector/up.sql b/migrations/2024-06-20-142013_collect_billing_details_from_wallet_connector/up.sql new file mode 100644 index 00000000000..edfda3f468b --- /dev/null +++ b/migrations/2024-06-20-142013_collect_billing_details_from_wallet_connector/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here + +ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS collect_billing_details_from_wallet_connector BOOLEAN DEFAULT FALSE; \ No newline at end of file
2024-06-20T17:11:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We were always passing in some parameters in the wallet session token in order to collect the billing details form the wallet connectors (like google pay and apple pay) always. Instead of collecting it always this feature adds a field (`collect_billing_details_from_wallet_connector`) in the business profile which if set to `true` we will add some fields in the session token to collect the shipping details from the wallet connectors. Reference: https://github.com/juspay/hyperswitch/pull/4601 ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant connector account -> Use the below curl to set the `collect_billing_details_from_wallet_connector` ``` curl --location 'http://localhost:8080/account/merchant_1718903636/business_profile/pro_D1HEnlPrKdJ33sefpb8W' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_billing_details_from_wallet_connector": false }' ``` <img width="940" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/69f7a1fe-89b6-446e-8461-a98fc82f1d7f"> -> Create a payment with confirm false ``` { "amount": 6500, "currency": "USD", "confirm": false, "amount_to_capture": 6500, "customer_id": "test_priority_routing", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "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" } } } ``` <img width="1046" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e9726e0b-31e5-4f91-b83b-9db2fdc750ec"> -> Make a session call for the above payment id and client secret ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_f0a9fbe61ae744049578ca94244364b6' \ --data '{ "payment_id": "pay_eX276M1t9ndwv0elPVHj", "wallets": [], "client_secret": "pay_eX276M1t9ndwv0elPVHj_secret_wjXQi2f5fRJkrhJWIbcs" }' ``` <img width="1142" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/50ca5b99-29cf-4027-85a9-7c94bb41b7ab"> <img width="1167" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4081beed-f425-48df-8950-22519b780abc"> In the above screenshots we can see that there is no billing details parameter for apple pay and for google pay its set to false as it is `collect_billing_details_from_wallet_connector` is set to false. -> Set the `collect_billing_details_from_wallet_connector` to true <img width="895" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/07627b75-9162-4e8a-8350-09359a7281de"> -> Create a payment with confirm false and make a session call <img width="1132" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/adf90bce-bf83-44d7-9dde-81718c7b989e"> <img width="706" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/62a0aa47-20ac-4e8e-a8d9-919f5ec15efe"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
7004a802de2d30b97ecd37f57ba0e9c3aa962993
juspay/hyperswitch
juspay__hyperswitch-5060
Bug: fix(payment_methods): support last used for off session token payments ### Feature Description support last used for off session token payments ### Possible Implementation support last used for off session token payments ### 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/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index f14997b20aa..b1bb3bb3c56 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3808,21 +3808,17 @@ pub async fn set_default_payment_method( } pub async fn update_last_used_at( - pm_id: &str, + payment_method: &diesel_models::PaymentMethod, state: &routes::SessionState, storage_scheme: MerchantStorageScheme, ) -> errors::RouterResult<()> { let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate { last_used_at: common_utils::date_time::now(), }; - let payment_method = state - .store - .find_payment_method(pm_id, storage_scheme) - .await - .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + state .store - .update_payment_method(payment_method, update_last_used, storage_scheme) + .update_payment_method(payment_method.clone(), update_last_used, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update the last_used_at in db")?; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 0c696c1b830..d87bdb62861 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1767,11 +1767,11 @@ pub async fn retrieve_payment_method_with_temporary_token( pub async fn retrieve_card_with_permanent_token( state: &SessionState, locker_id: &str, - payment_method_id: &str, + _payment_method_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&CardToken>, _merchant_key_store: &domain::MerchantKeyStore, - storage_scheme: enums::MerchantStorageScheme, + _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<api::PaymentMethodData> { let customer_id = payment_intent .customer_id @@ -1825,7 +1825,7 @@ pub async fn retrieve_card_with_permanent_token( card_issuing_country: None, bank_code: None, }; - cards::update_last_used_at(payment_method_id, state, storage_scheme).await?; + Ok(api::PaymentMethodData::Card(api_card)) } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 4843d1145d5..208c24d3590 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -113,6 +113,21 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|address| address.get_optional_full_name()); + if let Some(payment_method_info) = &payment_data.payment_method_info { + if payment_data.payment_intent.off_session.is_none() && resp.response.is_ok() { + payment_methods::cards::update_last_used_at( + payment_method_info, + state, + merchant_account.storage_scheme, + ) + .await + .map_err(|e| { + logger::error!("Failed to update last used at: {:?}", e); + }) + .ok(); + } + }; + let save_payment_call_future = Box::pin(tokenization::save_payment_method( state, connector_name.clone(),
2024-06-19T09:39:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Earlier, while doing an off_session payment token , the last used was not getting updated. This PR fixes that issue ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? - Create a MA and a MCA - Create a payment with > One card > Other card > then GooglePay - Now make a off_Session payment_token payment, with the first card, which is `4242` - List the PM for Customer, you would get the updated list , where card `4242` would come at the top and then the other pm ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d76ce2beaedcc09351dcfb70e27940c42a31c35d
juspay/hyperswitch
juspay__hyperswitch-5059
Bug: bug(events): update the ApiEventsType for `PaymentsSessionResponse` to use payments flow update the `ApiEventMetric` trait for this response to return `ApiEventsType::Payment { payment_id : String}` variant. based on the payment id stored in its body This would help for better structuring and help list this api call in the dashboard events as well
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index bed46f01f19..fd974a8b9e2 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -40,7 +40,6 @@ impl ApiEventMetric for TimeRange {} impl_misc_api_event_type!( PaymentMethodId, - PaymentsSessionResponse, PaymentMethodCreate, PaymentLinkInitiateRequest, RetrievePaymentLinkResponse, diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 4ed4e006669..ad2e2546f37 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -16,7 +16,7 @@ use crate::{ PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest, - PaymentsStartRequest, RedirectionResponse, + PaymentsSessionResponse, PaymentsStartRequest, RedirectionResponse, }, }; impl ApiEventMetric for PaymentsRetrieveRequest { @@ -248,3 +248,11 @@ impl ApiEventMetric for PaymentsManualUpdateRequest { }) } } + +impl ApiEventMetric for PaymentsSessionResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.payment_id.clone(), + }) + } +}
2024-06-26T10:56:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> Updated the `ApiEventMetric` trait to return `ApiEventsType::Payment { payment_id : String}` variant. Fixes #5059 <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I reviewed the submitted code
9c49ded104b81f1aefcc288e3ded64ebbd4d466f
juspay/hyperswitch
juspay__hyperswitch-5063
Bug: [REFACTOR] spawn one subscriber thread for handling all the published messages to different channel In the current Redis pub-sub implementation, a subscriber spawns a thread to handle all messages published to a channel. As a result, if a subscriber is invoked multiple times (even for subscribing to the same channel), it creates multiple threads for handling messages, which is not the desired behaviour. Ideally, we want to have only one subscriber thread handling all messages published to different channels. To achieve this, we maintain an atomic boolean variable, initially set to `false`, indicating whether the subscriber handler thread has been spawned. This variable will be set to `true` during the first subscriber invocation, thus preventing the creation of multiple threads during subsequent subscriber invocations.
diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index dc4fd3bbc9c..fa35039800b 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -68,6 +68,7 @@ impl RedisClient { pub struct SubscriberClient { inner: fred::clients::SubscriberClient, + pub is_subscriber_handler_spawned: Arc<atomic::AtomicBool>, } impl SubscriberClient { @@ -83,7 +84,10 @@ impl SubscriberClient { .wait_for_connect() .await .change_context(errors::RedisError::RedisConnectionError)?; - Ok(Self { inner: client }) + Ok(Self { + inner: client, + is_subscriber_handler_spawned: Arc::new(atomic::AtomicBool::new(false)), + }) } } diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rs index fb399a7084f..575481793ca 100644 --- a/crates/router/src/db/configs.rs +++ b/crates/router/src/db/configs.rs @@ -72,7 +72,7 @@ impl ConfigInterface for Store { self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .publish( - cache::PUB_SUB_CHANNEL, + cache::IMC_INVALIDATION_CHANNEL, CacheKind::Config((&inserted.key).into()), ) .await @@ -179,7 +179,10 @@ impl ConfigInterface for Store { self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .publish(cache::PUB_SUB_CHANNEL, CacheKind::Config(key.into())) + .publish( + cache::IMC_INVALIDATION_CHANNEL, + CacheKind::Config(key.into()), + ) .await .map_err(Into::<errors::StorageError>::into)?; diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 58b5b56fd21..38f859c48e7 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -74,7 +74,7 @@ pub async fn get_store( tenant, master_enc_key, cache_store, - storage_impl::redis::cache::PUB_SUB_CHANNEL, + storage_impl::redis::cache::IMC_INVALIDATION_CHANNEL, ) .await? }; diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 46aa3f8aa96..036a8902bc3 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -21,7 +21,7 @@ use crate::{ }; /// Redis channel name used for publishing invalidation messages -pub const PUB_SUB_CHANNEL: &str = "hyperswitch_invalidate"; +pub const IMC_INVALIDATION_CHANNEL: &str = "hyperswitch_invalidate"; /// Prefix for config cache key const CONFIG_CACHE_PREFIX: &str = "config"; @@ -392,7 +392,7 @@ pub async fn publish_into_redact_channel<'a, K: IntoIterator<Item = CacheKind<'a let futures = keys.into_iter().map(|key| async { redis_conn .clone() - .publish(PUB_SUB_CHANNEL, key) + .publish(IMC_INVALIDATION_CHANNEL, key) .await .change_context(StorageError::KVError) }); diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs index a50de0a4edd..670ffbb54e1 100644 --- a/crates/storage_impl/src/redis/pub_sub.rs +++ b/crates/storage_impl/src/redis/pub_sub.rs @@ -1,3 +1,5 @@ +use std::sync::atomic; + use error_stack::ResultExt; use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue}; use router_env::{logger, tracing::Instrument}; @@ -32,15 +34,29 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { .await .change_context(redis_errors::RedisError::SubscribeError)?; - let redis_clone = self.clone(); - let _task_handle = tokio::spawn( - async move { - if let Err(pubsub_error) = redis_clone.on_message().await { - logger::error!(?pubsub_error); + // Spawn only one thread handling all the published messages to different channels + if self + .subscriber + .is_subscriber_handler_spawned + .compare_exchange( + false, + true, + atomic::Ordering::SeqCst, + atomic::Ordering::SeqCst, + ) + .is_ok() + { + let redis_clone = self.clone(); + let _task_handle = tokio::spawn( + async move { + if let Err(pubsub_error) = redis_clone.on_message().await { + logger::error!(?pubsub_error); + } } - } - .in_current_span(), - ); + .in_current_span(), + ); + } + Ok(()) } @@ -61,120 +77,131 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { logger::debug!("Started on message: {:?}", self.key_prefix); let mut rx = self.subscriber.on_message(); while let Ok(message) = rx.recv().await { - logger::debug!("Invalidating {message:?}"); - let key = match CacheKind::try_from(RedisValue::new(message.value)) - .change_context(redis_errors::RedisError::OnMessageError) - { - Ok(value) => value, - Err(err) => { - logger::error!(value_conversion_err=?err); - continue; - } - }; - - let key = match key { - CacheKind::Config(key) => { - CONFIG_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - key - } - CacheKind::Accounts(key) => { - ACCOUNTS_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - key - } - CacheKind::CGraph(key) => { - CGRAPH_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - key - } - CacheKind::Routing(key) => { - ROUTING_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - key - } - CacheKind::DecisionManager(key) => { - DECISION_MANAGER_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - key - } - CacheKind::Surcharge(key) => { - SURCHARGE_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - key - } - CacheKind::All(key) => { - CONFIG_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - ACCOUNTS_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - CGRAPH_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - ROUTING_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - DECISION_MANAGER_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - SURCHARGE_CACHE - .remove(CacheKey { - key: key.to_string(), - prefix: self.key_prefix.clone(), - }) - .await; - - key - } - }; + let channel_name = message.channel.to_string(); + logger::debug!("Received message on channel: {channel_name}"); + + match channel_name.as_str() { + super::cache::IMC_INVALIDATION_CHANNEL => { + let key = match CacheKind::try_from(RedisValue::new(message.value)) + .change_context(redis_errors::RedisError::OnMessageError) + { + Ok(value) => value, + Err(err) => { + logger::error!(value_conversion_err=?err); + continue; + } + }; + + let key = match key { + CacheKind::Config(key) => { + CONFIG_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key + } + CacheKind::Accounts(key) => { + ACCOUNTS_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key + } + CacheKind::CGraph(key) => { + CGRAPH_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key + } + CacheKind::Routing(key) => { + ROUTING_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key + } + CacheKind::DecisionManager(key) => { + DECISION_MANAGER_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key + } + CacheKind::Surcharge(key) => { + SURCHARGE_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key + } + CacheKind::All(key) => { + CONFIG_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + ACCOUNTS_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + CGRAPH_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + ROUTING_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + DECISION_MANAGER_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + SURCHARGE_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; - self.delete_key(key.as_ref()) - .await - .map_err(|err| logger::error!("Error while deleting redis key: {err:?}")) - .ok(); + key + } + }; - logger::debug!("Done invalidating {key}"); + self.delete_key(key.as_ref()) + .await + .map_err(|err| logger::error!("Error while deleting redis key: {err:?}")) + .ok(); + + logger::debug!( + "Handled message on channel {channel_name} - Done invalidating {key}" + ); + } + _ => { + logger::debug!("Received message from unknown channel: {channel_name}"); + } + } } Ok(()) }
2024-06-20T15:44:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> In the current Redis pub-sub implementation, a subscriber spawns a thread to handle all messages published to a channel. As a result, if a subscriber is invoked multiple times (even for subscribing to the same channel), it creates multiple threads for handling messages, which is not the desired behaviour. Ideally, we want to have only one subscriber thread handling all messages published to different channels. To achieve this, we maintain an atomic boolean variable, initially set to `false`, indicating whether the subscriber handler thread has been spawned. This variable will be set to `true` during the first subscriber invocation, thus preventing the creation of multiple threads during subsequent subscriber invocations. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> In the current implementation, the subscriber has been invoked 2 times thus resulting in 2 threads being spawned. Consequently, cache invalidation attempts occur in both threads, with only one succeeding. With this PR, there'll always be only one subscriber thread responsible for invalidating the cache entry. * Send a request to the `/configs` endpoint to add a new test config. ``` curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "key": "test_key", "value": "test_val" }' ``` * This action triggers cache invalidation. * Check the request logs. You should see only one log entry stating: "Done invalidating test_key" ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ca61e47585071865cf7df5c05fdbe3f57818ca95
juspay/hyperswitch
juspay__hyperswitch-5055
Bug: [FEATURE] Add a balance check for bank account during AIS flow ### Feature Description For the open banking AIS flow, we need to add a check o the available balance in the selected bank account while doing a payment. If the check fails, the payment should not go through. ### Possible Implementation Just a few type changes and a check in core should work ### 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/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs index 9d903914483..8ce5aca7b83 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::{PaymentMethod, PaymentMethodType}; -use common_utils::id_type; +use common_utils::{id_type, types as util_types}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -120,7 +120,7 @@ pub struct PlaidBankAccountCredentialsRequest { options: Option<BankAccountCredentialsOptions>, } -#[derive(Debug, Deserialize, Eq, PartialEq)] +#[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsResponse { pub accounts: Vec<PlaidBankAccountCredentialsAccounts>, @@ -135,19 +135,20 @@ pub struct BankAccountCredentialsOptions { account_ids: Vec<String>, } -#[derive(Debug, Deserialize, Eq, PartialEq)] +#[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsAccounts { pub account_id: String, pub name: String, pub subtype: Option<String>, + pub balances: Option<PlaidBankAccountCredentialsBalances>, } -#[derive(Debug, Deserialize, Eq, PartialEq)] +#[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsBalances { - pub available: Option<i32>, - pub current: Option<i32>, - pub limit: Option<i32>, + pub available: Option<util_types::FloatMajorUnit>, + pub current: Option<util_types::FloatMajorUnit>, + pub limit: Option<util_types::FloatMajorUnit>, pub iso_currency_code: Option<String>, pub unofficial_currency_code: Option<String>, pub last_updated_datetime: Option<String>, @@ -242,16 +243,27 @@ impl<F, T> let mut id_to_subtype = HashMap::new(); accounts_info.into_iter().for_each(|acc| { - id_to_subtype.insert(acc.account_id, (acc.subtype, acc.name)); + id_to_subtype.insert( + acc.account_id, + ( + acc.subtype, + acc.name, + acc.balances.and_then(|balance| balance.available), + ), + ); }); account_numbers.ach.into_iter().for_each(|ach| { - let (acc_type, acc_name) = - if let Some((_type, name)) = id_to_subtype.get(&ach.account_id) { - (_type.to_owned(), Some(name.clone())) - } else { - (None, None) - }; + let (acc_type, acc_name, available_balance) = if let Some(( + _type, + name, + available_balance, + )) = id_to_subtype.get(&ach.account_id) + { + (_type.to_owned(), Some(name.clone()), *available_balance) + } else { + (None, None, None) + }; let account_details = types::PaymentMethodTypeDetails::Ach(types::BankAccountDetailsAch { @@ -266,17 +278,19 @@ impl<F, T> payment_method: PaymentMethod::BankDebit, account_id: ach.account_id.into(), account_type: acc_type, + balance: available_balance, }; 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())) + let (acc_type, acc_name, available_balance) = + if let Some((_type, name, available_balance)) = id_to_subtype.get(&bacs.account_id) + { + (_type.to_owned(), Some(name.clone()), *available_balance) } else { - (None, None) + (None, None, None) }; let account_details = @@ -292,17 +306,19 @@ impl<F, T> payment_method: PaymentMethod::BankDebit, account_id: bacs.account_id.into(), account_type: acc_type, + balance: available_balance, }; 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())) + let (acc_type, acc_name, available_balance) = + if let Some((_type, name, available_balance)) = id_to_subtype.get(&sepa.account_id) + { + (_type.to_owned(), Some(name.clone()), *available_balance) } else { - (None, None) + (None, None, None) }; let account_details = @@ -318,6 +334,7 @@ impl<F, T> payment_method: PaymentMethod::BankDebit, account_id: sepa.account_id.into(), account_type: acc_type, + balance: available_balance, }; bank_account_vec.push(bank_details_new); diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs index f2a848c2f60..2537cdc6a36 100644 --- a/crates/pm_auth/src/types.rs +++ b/crates/pm_auth/src/types.rs @@ -4,7 +4,7 @@ use std::marker::PhantomData; use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}; use common_enums::{PaymentMethod, PaymentMethodType}; -use common_utils::id_type; +use common_utils::{id_type, types}; use masking::Secret; #[derive(Debug, Clone)] pub struct PaymentAuthRouterData<F, Request, Response> { @@ -78,6 +78,7 @@ pub struct BankAccountDetails { pub payment_method: PaymentMethod, pub account_id: Secret<String>, pub account_type: Option<String>, + pub balance: Option<types::FloatMajorUnit>, } #[derive(Debug, Clone)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 41007286b83..dad7bd79248 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2021,7 +2021,10 @@ pub async fn list_payment_methods( .await .transpose()?; - let mut pmt_to_auth_connector = HashMap::new(); + let mut pmt_to_auth_connector: HashMap< + enums::PaymentMethod, + HashMap<enums::PaymentMethodType, String>, + > = HashMap::new(); if let Some((payment_attempt, payment_intent)) = payment_attempt.as_ref().zip(payment_intent.as_ref()) @@ -2195,24 +2198,35 @@ pub async fn list_payment_methods( 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) = pm_auth_config { + config + .enabled_payment_methods + .iter() + .for_each(|inner_config| { + if inner_config.payment_method_type == *payment_method_type { + let pm = pmt_to_auth_connector + .get(&inner_config.payment_method) + .cloned(); + + let inner_map = if let Some(mut inner_map) = pm { + inner_map.insert( + *payment_method_type, + inner_config.connector_name.clone(), + ); + inner_map + } else { + HashMap::from([( + *payment_method_type, + inner_config.connector_name.clone(), + )]) + }; + + pmt_to_auth_connector + .insert(inner_config.payment_method, inner_map); + val.push(inner_config.clone()); + } + }); }; - - if let Some(config) = matched_config { - pmt_to_auth_connector - .insert(*payment_method_type, config.connector_name.clone()); - val.push(config); - } } } @@ -2522,7 +2536,8 @@ pub async fn list_payment_methods( .cloned(), surcharge_details: None, pm_auth_connector: pmt_to_auth_connector - .get(payment_method_types_hm.0) + .get(key.0) + .and_then(|pm_map| pm_map.get(payment_method_types_hm.0)) .cloned(), }) } @@ -2559,7 +2574,8 @@ pub async fn list_payment_methods( .cloned(), surcharge_details: None, pm_auth_connector: pmt_to_auth_connector - .get(payment_method_types_hm.0) + .get(key.0) + .and_then(|pm_map| pm_map.get(payment_method_types_hm.0)) .cloned(), }) } @@ -2590,7 +2606,10 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), + pm_auth_connector: pmt_to_auth_connector + .get(&enums::PaymentMethod::BankRedirect) + .and_then(|pm_map| pm_map.get(key.0)) + .cloned(), } }) } @@ -2623,7 +2642,10 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), + pm_auth_connector: pmt_to_auth_connector + .get(&enums::PaymentMethod::BankDebit) + .and_then(|pm_map| pm_map.get(key.0)) + .cloned(), } }) } @@ -2656,7 +2678,10 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), + pm_auth_connector: pmt_to_auth_connector + .get(&enums::PaymentMethod::BankTransfer) + .and_then(|pm_map| pm_map.get(key.0)) + .cloned(), } }) } diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index e78c2153bb7..508b9e8ef8b 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -15,6 +15,7 @@ use common_utils::{ crypto::{HmacSha256, SignMessage}, ext_traits::AsyncExt, generate_id, + types::{self as util_types, AmountConvertor}, }; use error_stack::ResultExt; use helpers::PaymentAuthConnectorDataExt; @@ -66,6 +67,19 @@ pub async fn create_link_token( let pm_auth_key = format!("pm_auth_{}", payload.payment_id); + redis_conn + .exists::<Vec<u8>>(&pm_auth_key) + .await + .change_context(ApiErrorResponse::InvalidRequestData { + message: "Incorrect payment_id provided in request".to_string(), + }) + .attach_printable("Corresponding pm_auth_key does not exist in redis")? + .then_some(()) + .ok_or(ApiErrorResponse::InvalidRequestData { + message: "Incorrect payment_id provided in request".to_string(), + }) + .attach_printable("Corresponding pm_auth_key does not exist in redis")?; + let pm_auth_configs = redis_conn .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( pm_auth_key.as_str(), @@ -637,6 +651,19 @@ async fn get_selected_config_from_redis( let pm_auth_key = format!("pm_auth_{}", payload.payment_id); + redis_conn + .exists::<Vec<u8>>(&pm_auth_key) + .await + .change_context(ApiErrorResponse::InvalidRequestData { + message: "Incorrect payment_id provided in request".to_string(), + }) + .attach_printable("Corresponding pm_auth_key does not exist in redis")? + .then_some(()) + .ok_or(ApiErrorResponse::InvalidRequestData { + message: "Incorrect payment_id provided in request".to_string(), + }) + .attach_printable("Corresponding pm_auth_key does not exist in redis")?; + let pm_auth_configs = redis_conn .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( pm_auth_key.as_str(), @@ -720,6 +747,21 @@ pub async fn retrieve_payment_method_from_auth_service( .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Bank account details not found")?; + if let (Some(balance), Some(currency)) = (bank_account.balance, payment_intent.currency) { + let required_conversion = util_types::FloatMajorUnitForConnector; + let converted_amount = required_conversion + .convert_back(balance, currency) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Could not convert FloatMajorUnit to MinorUnit")?; + + if converted_amount < payment_intent.amount { + return Err((ApiErrorResponse::PreconditionFailed { + message: "selected bank account has insufficient balance".to_string(), + }) + .into()); + } + } + let mut bank_type = None; if let Some(account_type) = bank_account.account_type.clone() { bank_type = common_enums::BankType::from_str(account_type.as_str())
2024-06-20T10:40:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> have added a balance check that would enable a check on the available amount in the selected bank account while doing a payment. If the found balance is less than the intent amount, the payment would not go through. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Follow this for TCs - https://github.com/juspay/hyperswitch/pull/3047 In the payment create, use amount greater then 150 USD for the check to work - Payment create - ``` curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_0u355Qt5nbq8BhTZtWmbkwzQJ4JY77u0jOpjyIi3LRqIFziLTFKI8E6QwgFmaFc5' \ --data-raw '{ "amount": 65400, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 65400, "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" } }' ``` - Payment confirm ``` curl --location --request POST 'http://localhost:8080/payments/pay_FKpvykZd46XL9grQwPlC/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_9cdfbdb024614790a4bf730b19a8c375' \ --data-raw '{ "payment_token": "token_Yxogj2YxdeHjC316ZtM9", "client_secret": "pay_FKpvykZd46XL9grQwPlC_secret_KQLB47ADsiyrIhIpOvxv", "payment_method": "bank_debit", "payment_method_type": "ach" }' ``` Response ``` { "error": { "type": "invalid_request", "message": "Payment amount is greater than the available amount in selected bank account", "code": "IR_06" } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f3fb59ce7448f91b74d0be4a75d82e282f075a66
juspay/hyperswitch
juspay__hyperswitch-5047
Bug: [BUG] Cypress tests are being skipped This bug came into existence after some of the tests started to fail from server side error. Commit that caused: [`24217d1` (#4904)](https://github.com/juspay/hyperswitch/pull/4904/commits/24217d132f87c31ecb2a44ac6340425d26750a5f). Reverting this should suffice.
2024-06-19T16:36:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR fixes error introduced in commit [`24217d1` (#4904)](https://github.com/juspay/hyperswitch/pull/4904/commits/24217d132f87c31ecb2a44ac6340425d26750a5f) of PR https://github.com/juspay/hyperswitch/pull/4904 which led to tests getting skipped on single test failure which went unnoticed (After this change, when I ran the tests, things were working fine, not sure what went down the line). But that commit seems to fix it. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 #5047 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Wrote below script to run tests in parallel (parallel tests require a lot of resource, else, tests become flaky): ```sh #! /bin/bash # DECLARATIONS export DEBUG=cypress:cli # Set the environment variables for the tests before running them export CYPRESS_BASEURL="http://localhost:8080" export CYPRESS_ADMINAPIKEY='test_admin' export CYPRESS_CONNECTOR_AUTH_FILE_PATH='${HOME}/creds.json' CONNECTORS=("adyen" "bankofamerica" "bluesnap" "cybersource" "nmi" "paypal" "stripe" "trustpay") export CYPRESS_HS_EMAIL='example@email.com' export CYPRESS_HS_PASSWORD='secret_password' mkdir -p results for connector in "${CONNECTORS[@]}"; do CYPRESS_CONNECTOR="${connector}" npm run cypress:ci > results/${connector}.txt 2>&1 & done wait ``` ETA: <img width="429" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/865830fa-950e-43cf-8751-8541cfb5a065"> Parallel Tests (Ran it after PC cooled down and had available resources) |Adyen|Bank of America|Bluesnap|Cybersource| |-|-|-|-| |<img width="402" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/ae64044d-dc68-4ff5-86b3-a8833278c6cf">|<img width="403" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/61bb91cf-85bc-401f-965c-3e1ae6b7fb26">|<img width="399" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/2e893adc-8cca-45bd-868a-0be22861e8a2">|<img width="402" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/5494038c-a0c3-4dfb-b62e-63da237ef613">| |NMI|PayPal|Stripe|Trustpay| |<img width="402" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/f7b06dfd-0f27-48b7-bd1b-c9b7f909c261">|<img width="402" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/f9daa879-1fd7-48ff-85c2-c4955464d343">|<img width="404" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/b5b262ec-7dbb-4ade-a10b-713c46b255b5">|<img width="402" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/d16b7bf3-0d28-42aa-b7aa-fc20b607caab">| > [!IMPORTANT] > When running in parallel, Bluesnap and NMI have higher failure rates compared to other connectors. RCA has to be done. It is not a priority as of now. One test at a time |Adyen|Bank of America|Bluesnap|Cybersource| |-|-|-|-| |<img width="405" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/cf7688d8-2a0e-4f52-b8fb-499757c23e0e">|<img width="403" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/11d76cfa-ae8a-4ccb-8b7b-bf20985d5c1d">|<img width="404" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/ed281016-dc41-4be6-9e2c-2fff1ee37216">|<img width="406" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/5feb53cf-bf0f-40e7-9851-209ae275369d">| |NMI|PayPal|Stripe|Trustpay| |<img width="405" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/061bfb47-5f95-42f3-89d5-91e717680d1d">|<img width="403" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/75b3419d-f96b-42a8-a53b-e0297a0e4a5f">|<img width="401" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/7474af5e-7fbe-4b4e-9ef3-995b47ae1e6d">|<img width="408" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/c57816fc-925b-4e41-93e1-592e4bd37418">| > [!IMPORTANT] > Trustpay failing is server side issue. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
45a908b4407db160b5f92b0bf84a9612cfaf44ef
juspay/hyperswitch
juspay__hyperswitch-5037
Bug: [FEATURE] Add logger for sessions call failure ### Feature Description Add a logger for failure of sessions call when the call fails at connector's end. ### Possible Implementation Add a logger for failure of sessions call when the call fails at connector's end. ### 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/payments.rs b/crates/router/src/core/payments.rs index d459fef935e..8935c3ac0ee 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1740,7 +1740,7 @@ where if let Ok(router_types::PaymentsResponseData::SessionResponse { session_token, .. - }) = connector_response.response + }) = connector_response.response.clone() { // If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error // In case of error, that error is already logged @@ -1751,13 +1751,16 @@ where payment_data.sessions_token.push(session_token); } } + if let Err(connector_error_response) = connector_response.response { + logger::error!( + "sessions_connector_error {} {:?}", + connector_name, + connector_error_response + ); + } } - Err(connector_error) => { - logger::error!( - "sessions_connector_error {} {:?}", - connector_name, - connector_error - ); + Err(api_error) => { + logger::error!("sessions_api_error {} {:?}", connector_name, api_error); } } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 518d1aa1a79..0c6ce07e51a 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -332,6 +332,7 @@ where if let Some(status) = error_res.attempt_status { router_data.status = status; }; + state.event_handler().log_event(&connector_event); error_res } };
2024-06-19T08:06:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add a logger for failure of sessions call when the call fails at connector's end. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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/5037 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> The following logs should be checked: 1. Session call fails without calling connector: - Payments Create(Klarna): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jOiTovkpGinwxAIGAlEyC9SiVkJCfK3Tc1NNOntnkLMaeaM7U7xtde8a88LhPVlm' \ --data-raw '{ "amount": 6500, "client_secret": "pay_QWcuxERT26fPFELkA1d6_secret_m9LRWGDRVRckiKvfnNUZ", "currency": "USD", "customer_id": "cdsdcwmn", "customer": { "id": "cdsdcwmn", "email": "user@gmail.com" }, "confirm": false, "description": "Hello this is description", "setup_future_usage": "on_session", "capture_method": "automatic", "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "444, Stelar Enclave", "line2": "California", "line3": "Groningen", "city": "Groningen", "state": "Groningen", "zip": "94105", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "446681800", "country_code": "+41" } }, "order_details": [ { "amount": 6500, "quantity": 1, "product_name": "Apple iphone 15" } ], "email": "user@gmail.com", "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" } }' ``` Response: ``` { "payment_id": "pay_tVGVQM83dIDCw3ruJ2rW", "merchant_id": "merchant_1718782884", "status": "requires_payment_method", "amount": 6500, "net_amount": 6500, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_tVGVQM83dIDCw3ruJ2rW_secret_5yzEyo6XRKmikqS1mAvM", "created": "2024-06-19T08:02:28.968Z", "currency": "USD", "customer_id": "cdsdcwmn", "customer": { "id": "cdsdcwmn", "name": null, "email": "user@gmail.com", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "Groningen", "country": "US", "line1": "444, Stelar Enclave", "line2": "California", "line3": "Groningen", "zip": "94105", "state": "Groningen", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "446681800", "country_code": "+41" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "brand": null, "amount": 6500, "category": null, "quantity": 1, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "requires_shipping": null } ], "email": "user@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cdsdcwmn", "created_at": 1718784148, "expires": 1718787748, "secret": "epk_4f84615faf66473aa1a1344bb10d014a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_rDD29g488ZjT3dFTLs9s", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-19T08:17:28.968Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-19T08:02:28.986Z", "charges": null, "frm_metadata": null } ``` - Session Token: Request: ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_d36f99efb52a4dd891bca3d9bd9c8842' \ --data '{ "payment_id": "pay_tVGVQM83dIDCw3ruJ2rW", "wallets": [], "client_secret": "pay_tVGVQM83dIDCw3ruJ2rW_secret_5yzEyo6XRKmikqS1mAvM" }' ``` Response: ``` { "payment_id": "pay_tVGVQM83dIDCw3ruJ2rW", "client_secret": "pay_tVGVQM83dIDCw3ruJ2rW_secret_5yzEyo6XRKmikqS1mAvM", "session_token": [] } ``` Logs: <img width="1308" alt="Screenshot 2024-06-19 at 1 33 09 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/9eba4aba-687b-42b1-86cb-048ef19a1d79"> 2. Session Call fails at connector: NOTE: To generate this error enter wrong api credentials for Klarna while creating the connector - Payments Create (Klarna): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jOiTovkpGinwxAIGAlEyC9SiVkJCfK3Tc1NNOntnkLMaeaM7U7xtde8a88LhPVlm' \ --data-raw '{ "amount": 6500, "client_secret": "pay_QWcuxERT26fPFELkA1d6_secret_m9LRWGDRVRckiKvfnNUZ", "currency": "USD", "customer_id": "cdsdcwmn", "customer": { "id": "cdsdcwmn", "email": "user@gmail.com" }, "confirm": false, "description": "Hello this is description", "setup_future_usage": "on_session", "capture_method": "automatic", "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "order_details": [ { "amount": 6500, "quantity": 1, "product_name": "Apple iphone 15" } ], "email": "user@gmail.com", "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" } }' ``` Response: ``` { "payment_id": "pay_eJNLxe3merOzC4Ne0yBk", "merchant_id": "merchant_1718782884", "status": "requires_payment_method", "amount": 6500, "net_amount": 6500, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_eJNLxe3merOzC4Ne0yBk_secret_e8cDuFl2f0flJTbXnx9s", "created": "2024-06-19T08:14:18.074Z", "currency": "USD", "customer_id": "cdsdcwmn", "customer": { "id": "cdsdcwmn", "name": null, "email": "user@gmail.com", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "brand": null, "amount": 6500, "category": null, "quantity": 1, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "requires_shipping": null } ], "email": "user@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cdsdcwmn", "created_at": 1718784858, "expires": 1718788458, "secret": "epk_c15cf7f5abb74cc79d7d5135d7b7bbf1" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_rDD29g488ZjT3dFTLs9s", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-19T08:29:18.073Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-19T08:14:18.149Z", "charges": null, "frm_metadata": null } ``` - Session Token: Request: ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_d36f99efb52a4dd891bca3d9bd9c8842' \ --data '{ "payment_id": "pay_eJNLxe3merOzC4Ne0yBk", "wallets": [], "client_secret": "pay_eJNLxe3merOzC4Ne0yBk_secret_e8cDuFl2f0flJTbXnx9s" }' ``` Response: ``` { "payment_id": "pay_eJNLxe3merOzC4Ne0yBk", "client_secret": "pay_eJNLxe3merOzC4Ne0yBk_secret_e8cDuFl2f0flJTbXnx9s", "session_token": [] } ``` Logs: <img width="1308" alt="Screenshot 2024-06-19 at 1 32 03 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/0d5c5c74-59a1-4448-b933-15c60787bd66"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d76ce2beaedcc09351dcfb70e27940c42a31c35d
juspay/hyperswitch
juspay__hyperswitch-5024
Bug: Add payment method type duplication check for `google_pay` Currently there is no duplication check for google pay and we will create a new payment method entry for every google pay payment CIT with `"setup_future_usage": "on_session"`. This is not the case in cards as locker handles the card duplication. Since we do not have a parameter handle duplication check for a google pay, we have to go with a approach of a customer can have only one saved google pay payment method. In this approach we list all the saved payment method for a customer during every google pay CIT and check if any of them have the `payment_method_type` is `google_pay` if it is then we just return already saved `payment_method_id`.
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 2d5d216a856..f05a81b223f 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -515,8 +515,10 @@ where } }, None => { - let customer_apple_pay_saved_pm_id_option = if payment_method_type + let customer_saved_pm_id_option = if payment_method_type == Some(api_models::enums::PaymentMethodType::ApplePay) + || payment_method_type + == Some(api_models::enums::PaymentMethodType::GooglePay) { match state .store @@ -530,8 +532,7 @@ where Ok(customer_payment_methods) => Ok(customer_payment_methods .iter() .find(|payment_method| { - payment_method.payment_method_type - == Some(api_models::enums::PaymentMethodType::ApplePay) + payment_method.payment_method_type == payment_method_type }) .map(|pm| pm.payment_method_id.clone())), Err(error) => { @@ -552,10 +553,8 @@ where Ok(None) }?; - if let Some(customer_apple_pay_saved_pm_id) = - customer_apple_pay_saved_pm_id_option - { - resp.payment_method_id = customer_apple_pay_saved_pm_id; + if let Some(customer_saved_pm_id) = customer_saved_pm_id_option { + resp.payment_method_id = customer_saved_pm_id; } else { let pm_metadata = create_payment_method_metadata(None, connector_token)?;
2024-06-18T11:04:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently there is no duplication check for google pay and we will create a new payment method entry for every google pay payment CIT with `"setup_future_usage": "on_session"`. This is not the case in cards as locker handles the card duplication. Since we do not have a parameter handle duplication check for a google pay, we have to go with a approach of a customer can have only one saved google pay payment method. In this approach we list all the saved payment method for a customer during every google pay CIT and check if any of them have the `payment_method_type` is `google_pay` if it is then we just return already saved `payment_method_id`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant connector account with google pay enabled -> Do a CIT with `setup_future_usage` ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_rR35w9RzL1WW5hiDN7aF9jZbH6qHzAzW0nb9kB52KAnJDYc5EH3CakFbIje9MpYk' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 800, "currency": "USD", "confirm": true, "amount_to_capture": 800, "customer_id": "gpay_testing", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "type": "CARD", "description": "Visa •••• 1111", "info": { "card_network": "VISA", "card_details": "1111" }, "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{\n \"id\": \"tok_1PT1DcD5n \"address_line2\": null,\n \"address_state\": null,\n \"address_zip\": null,\n \"address,\n \"exp_year\": 2026,\n \"funding\": \"credit\",\n \"last4\": \"1111\",\n \"metadata\": {},\n \"name\": null,\n \"networks\": {\n \"preferred\": null\n },\n \"tokenization_method\": \"android_pay\",\n \"wallet\": null\n },\n \"client_ip\": \"209.85.198.162\",\n \"created\": 1718713980,\n \"livemode\": false,\n \"type\": \"card\",\n \"used\": false\n}" } } } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "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" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` <img width="804" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/b35b015e-d049-49fd-932f-aea4d421ca3a"> -> Perform the CIT again with same request payload and different google pay token ``` { "amount": 800, "currency": "USD", "confirm": true, "amount_to_capture": 800, "customer_id": "gpay_testing", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "type": "CARD", "description": "Visa •••• 1111", "info": { "card_network": "VISA", "card_details": "1111" }, "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{\n \"id\": \"tok_1PT1czD5R7gDAGffO2Mtj23f\",\n \"object\": \"token\",\n \"card\": {\n \"id\": \"card_1PT1czD5R7gDAGffPGZqUPoL\",\n \"object\": \"card\",\n \"address_city\": null,\n \"address_country\": null,\n \"address_line1\": null,\n \"address_line1_check\": null,\n \"address_line2\": null,\n \"address_state\": null,\n \"address_zip\": null,\n \"address_zip_check\": null,\n \"brand\": \"Visa\",\n \"country\": \"US\",\n \"cvc_check\": null,\n \"dynamic_last4\": \"1111\",\n \"exp_month\": 12,\n \"exp_year\": 2026,\n \"funding\": \"credit\",\n \"last4\": \"1111\",\n \"metadata\": {},\n \"name\": null,\n \"networks\": {\n \"preferred\": null\n },\n \"tokenization_method\": \"android_pay\",\n \"wallet\": null\n },\n \"client_ip\": \"209.85.198.162\",\n \"created\": 1718715553,\n \"livemode\": false,\n \"type\": \"card\",\n \"used\": false\n}" } } } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "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" } }, "connector_metadata": { "noon": { "order_category": "pay" } } } ``` <img width="1077" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/efe76f95-1253-4abd-b427-6f4dc4ec4021"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
a7ad7906d7e84fa59df3cfffd16dea8db300e675
juspay/hyperswitch
juspay__hyperswitch-5018
Bug: [FIX] populate card fields while saving card again during metadata change condition When the same card is being saved with metadata changes, the other fields of card like `card_network`, `card_issuer`, `scheme`, `card_type`, `card_isin`, `card_issuing_country` is getting saved with hardcoded value as `None` instead of getting its value from the existing saved card.
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 66940fa9508..ba2de78a6ac 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -653,9 +653,10 @@ pub async fn add_payment_method( }; let updated_card = Some(api::CardDetailFromLocker { - scheme: None, + scheme: existing_pm.scheme.clone(), last4_digits: Some(card.card_number.get_last4()), - issuer_country: None, + issuer_country: card.card_issuing_country, + card_isin: Some(card.card_number.get_card_isin()), card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), @@ -663,10 +664,9 @@ pub async fn add_payment_method( 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, + card_network: card.card_network, + card_issuer: card.card_issuer, + card_type: card.card_type, saved_to_locker: true, }); diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 21aa51b46a3..ca0cbb2a0f8 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -346,7 +346,7 @@ pub fn mk_add_card_response_hs( let card = api::CardDetailFromLocker { scheme: None, last4_digits: Some(last4_digits), - issuer_country: None, + issuer_country: card.card_issuing_country, card_number: Some(card.card_number.clone()), expiry_month: Some(card.card_exp_month.clone()), expiry_year: Some(card.card_exp_year.clone()), diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b014f42a5ce..c8a48252504 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -469,9 +469,10 @@ where }; let updated_card = Some(CardDetailFromLocker { - scheme: None, + scheme: existing_pm.scheme.clone(), last4_digits: Some(card.card_number.get_last4()), - issuer_country: None, + issuer_country: card.card_issuing_country, + card_isin: Some(card.card_number.get_card_isin()), card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), @@ -479,10 +480,9 @@ where 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, + card_network: card.card_network, + card_issuer: card.card_issuer, + card_type: card.card_type, saved_to_locker: true, });
2024-06-16T13:00:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> When the same card is being saved with metadata changes, the other fields of card like `card_network`, `card_issuer`, `scheme`, `card_type`, `card_isin`, `card_issuing_country` were getting saved with hardcoded value as `None` instead of getting its value from the existing saved card. This PR fixes the issue ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Save a card ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_bS3Uz99HdVusSOy9rHtZqcevmpHt9L4N6WvNt5d16SwBgz53crKKEd6pCMrvVVbH' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "cus_6Syv31iU1EeDKyfN1U7O", "email": "guest@example.com", "customer_acceptance": { "acceptance_type": "online" }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "Test Holder", "card_cvc": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "authentication_type": "no_three_ds" }' ``` 2. Hit list customer payment methods and all the card fields like card_network, issuer country, scheme, etc should be listed. ![image](https://github.com/juspay/hyperswitch/assets/70657455/04daa5d4-a8fd-4994-8bb2-b99c17e4a6d5) 3. Save the same card again but with some different expiry. 4. Hit list customer payment methods and still the above fields has to be listed which was not the case before. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40dfad89ac6e70a15321b3711ee4c05c3c2ff201
juspay/hyperswitch
juspay__hyperswitch-5015
Bug: Override the `setup_future_usage` field to `on_session` based on merchant config This is the use case where in which we need if the setup_future_usage is set to off_session in the payment method needs to be just saved at hyperswitch and not at connector. `skip_saving_wallet_at_connector_<merchant_id>` is the config which takes vector of payment method type as the value. When this config is set, the `setup_future_usage` is overridden to `on_session` by which mandates won't be created at the connector's end. ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "skip_saving_wallet_at_connector_merchant_1718351667", "value": "[\"apple_pay\"]" }' ``` Also add a validation to add duplicate apple pay payment method being saved.
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 50eedcfb568..b4ac878d372 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3558,6 +3558,25 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone Ok(ConnectorCallType::PreDetermined(chosen_connector_data)) } _ => { + let skip_saving_wallet_at_connector_optional = + helpers::config_skip_saving_wallet_at_connector( + &*state.store, + &payment_data.payment_intent.merchant_id, + ) + .await?; + + if let Some(skip_saving_wallet_at_connector) = skip_saving_wallet_at_connector_optional + { + if let Some(payment_method_type) = payment_data.payment_attempt.payment_method_type + { + if skip_saving_wallet_at_connector.contains(&payment_method_type) { + logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate."); + payment_data.payment_intent.setup_future_usage = + Some(enums::FutureUsage::OnSession); + } + } + }; + let first_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 7eada733aed..1a2f0a5cbaa 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4793,3 +4793,26 @@ pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>( pub fn get_redis_key_for_extended_card_info(merchant_id: &str, payment_id: &str) -> String { format!("{merchant_id}_{payment_id}_extended_card_info") } + +pub async fn config_skip_saving_wallet_at_connector( + db: &dyn StorageInterface, + merchant_id: &String, +) -> CustomResult<Option<Vec<storage_enums::PaymentMethodType>>, errors::ApiErrorResponse> { + let config = db + .find_config_by_key_unwrap_or( + format!("skip_saving_wallet_at_connector_{}", merchant_id).as_str(), + Some("[]".to_string()), + ) + .await; + Ok(match config { + Ok(conf) => Some( + serde_json::from_str::<Vec<storage_enums::PaymentMethodType>>(&conf.config) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("skip_save_wallet_at_connector config parsing failed")?, + ), + Err(err) => { + logger::error!("{err}"); + None + } + }) +} diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b014f42a5ce..2d5d216a856 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -515,35 +515,79 @@ where } }, None => { - let pm_metadata = create_payment_method_metadata(None, connector_token)?; - - locker_id = resp.payment_method.and_then(|pm| { - if pm == PaymentMethod::Card { - Some(resp.payment_method_id) - } else { - None + let customer_apple_pay_saved_pm_id_option = if payment_method_type + == Some(api_models::enums::PaymentMethodType::ApplePay) + { + match state + .store + .find_payment_method_by_customer_id_merchant_id_list( + &customer_id, + merchant_id, + None, + ) + .await + { + Ok(customer_payment_methods) => Ok(customer_payment_methods + .iter() + .find(|payment_method| { + payment_method.payment_method_type + == Some(api_models::enums::PaymentMethodType::ApplePay) + }) + .map(|pm| pm.payment_method_id.clone())), + Err(error) => { + if error.current_context().is_db_not_found() { + Ok(None) + } else { + Err(error) + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable( + "failed to find payment methods for a customer", + ) + } + } } - }); - - resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); - payment_methods::cards::create_payment_method( - db, - &payment_method_create_request, - &customer_id, - &resp.payment_method_id, - locker_id, - merchant_id, - pm_metadata, - customer_acceptance, - pm_data_encrypted, - key_store, - connector_mandate_details, - None, - network_transaction_id, - merchant_account.storage_scheme, - encrypted_payment_method_billing_address, - ) - .await?; + } else { + Ok(None) + }?; + + if let Some(customer_apple_pay_saved_pm_id) = + customer_apple_pay_saved_pm_id_option + { + resp.payment_method_id = customer_apple_pay_saved_pm_id; + } else { + let pm_metadata = + create_payment_method_metadata(None, connector_token)?; + + locker_id = resp.payment_method.and_then(|pm| { + if pm == PaymentMethod::Card { + Some(resp.payment_method_id) + } else { + None + } + }); + + resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); + payment_methods::cards::create_payment_method( + db, + &payment_method_create_request, + &customer_id, + &resp.payment_method_id, + locker_id, + merchant_id, + pm_metadata, + customer_acceptance, + pm_data_encrypted, + key_store, + connector_mandate_details, + None, + network_transaction_id, + merchant_account.storage_scheme, + encrypted_payment_method_billing_address, + ) + .await?; + }; } }
2024-06-15T08:17:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This is the use case where in which we need if the setup_future_usage is set to off_session in the payment method needs to be just saved at hyperswitch and not at connector. `skip_saving_wallet_at_connector_<merchant_id>` is the config which takes vector of payment method type as the value. When this config is set, the `setup_future_usage` is overridden to `on_session` by which mandates won't be created at the connector's end. ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "skip_saving_wallet_at_connector_merchant_1718351667", "value": "[\"apple_pay\"]" }' ``` Also add a validation to add duplicate apple pay payment method being saved. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant connector account -> Set below config for the merchant id ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "skip_saving_wallet_at_connector_merchant_1718351667", "value": "[\"apple_pay\"]" }' ``` -> Create a Apple pay CIT with `setup_future_usage = off_session` ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_EWsohyGByFVxgvYj8nbZbHTQObe6hRlLMS7rSKH2bFsySSjCc86Z6eOIH7tmLbUL' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 800, "currency": "USD", "confirm": true, "amount_to_capture": 800, "customer_id": "aaabbbcccdddeeee", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJ9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRRYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "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" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` <img width="992" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/57b0ffac-c806-4b0d-b933-68a5c79fcf58"> -> Retrieve the payment ``` curl --location 'http://localhost:8080/payments/pay_loeJ3oCXJWjjMsghuaId?expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_EWsohyGByFVxgvYj8nbZbHTQObe6hRlLMS7rSKH2bFsySSjCc86Z6eOIH7tmLbUL' ``` <img width="769" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/482c8ca3-6616-4ad2-bdc2-c6b08647d00b"> -> Do list customer payment methods ``` curl --location 'http://localhost:8080/customers/aaabbbcccdddeeee/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_EWsohyGByFVxgvYj8nbZbHTQObe6hRlLMS7rSKH2bFsySSjCc86Z6eOIH7tmLbUL' ``` <img width="895" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9e22fdcf-2c94-4401-81ee-deda17de0375"> -> Perform the CIT with the same request (for the same customer). After which perform the list customer payment methods and it should I have still only one apple pay payment method saved. -> Also for the above listed payment method verify there is no `connector_wallets_details` in the `payment_methods` table. <img width="1254" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9e1b4e9f-70a0-4c23-a16f-ba5cda2dc0f4"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40dfad89ac6e70a15321b3711ee4c05c3c2ff201
juspay/hyperswitch
juspay__hyperswitch-5025
Bug: enhancement(logging): Emit a setup error when a restricted keys are used for logging default keys Currently we have this error enum used for representing setup errors defined in https://github.com/juspay/hyperswitch/blob/main/crates/storage_impl/src/errors.rs#L158-L175 We can use this to represent the incorrect default fields error [here](https://github.com/juspay/hyperswitch/blob/99aa9d5d0aa7036b9e65853b5c99650156cff2cc/crates/router_env/src/logger/formatter.rs#L177) This would require moving the error enum to common_enums so it can be re-used.
diff --git a/Cargo.lock b/Cargo.lock index 68792185b1b..61dbacb522e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2002,6 +2002,7 @@ dependencies = [ "serde", "serde_json", "strum 0.26.2", + "thiserror", "utoipa", ] @@ -6197,6 +6198,7 @@ name = "router_env" version = "0.1.0" dependencies = [ "cargo_metadata 0.18.1", + "common_enums", "config", "error-stack", "gethostname", @@ -7216,6 +7218,7 @@ dependencies = [ "async-trait", "bb8", "bytes 1.6.0", + "common_enums", "common_utils", "config", "crc32fast", @@ -8417,9 +8420,9 @@ checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517" [[package]] name = "utf8parse" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "utoipa" diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index e364af0407d..c69676c01da 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -13,6 +13,7 @@ openapi = [] payouts = [] [dependencies] +thiserror = "1.0.58" diesel = { version = "2.1.5", features = ["postgres"] } serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 87d4f5e775a..a2dc924fcd0 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -20,6 +20,80 @@ pub mod diesel_exports { }; } +pub type ApplicationResult<T> = Result<T, ApplicationError>; + +#[derive(Debug, thiserror::Error)] +pub enum ApplicationError { + #[error("Application configuration error")] + ConfigurationError, + + #[error("Invalid configuration value provided: {0}")] + InvalidConfigurationValueError(String), + + #[error("Metrics error")] + MetricsError, + + #[error("I/O: {0}")] + IoError(std::io::Error), + + #[error("Error while constructing api client: {0}")] + ApiClientError(ApiClientError), +} + +#[derive(Debug, thiserror::Error, PartialEq, Clone)] +pub enum ApiClientError { + #[error("Header map construction failed")] + HeaderMapConstructionFailed, + #[error("Invalid proxy configuration")] + InvalidProxyConfiguration, + #[error("Client construction failed")] + ClientConstructionFailed, + #[error("Certificate decode failed")] + CertificateDecodeFailed, + #[error("Request body serialization failed")] + BodySerializationFailed, + #[error("Unexpected state reached/Invariants conflicted")] + UnexpectedState, + + #[error("URL encoding of request payload failed")] + UrlEncodingFailed, + #[error("Failed to send request to connector {0}")] + RequestNotSent(String), + #[error("Failed to decode response")] + ResponseDecodingFailed, + + #[error("Server responded with Request Timeout")] + RequestTimeoutReceived, + + #[error("connection closed before a message could complete")] + ConnectionClosedIncompleteMessage, + + #[error("Server responded with Internal Server Error")] + InternalServerErrorReceived, + #[error("Server responded with Bad Gateway")] + BadGatewayReceived, + #[error("Server responded with Service Unavailable")] + ServiceUnavailableReceived, + #[error("Server responded with Gateway Timeout")] + GatewayTimeoutReceived, + #[error("Server responded with unexpected response")] + UnexpectedServerResponse, +} +impl ApiClientError { + pub fn is_upstream_timeout(&self) -> bool { + self == &Self::RequestTimeoutReceived + } + pub fn is_connection_closed_before_message_could_complete(&self) -> bool { + self == &Self::ConnectionClosedIncompleteMessage + } +} + +impl From<std::io::Error> for ApplicationError { + fn from(err: std::io::Error) -> Self { + Self::IoError(err) + } +} + /// The status of the attempt #[derive( Clone, diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index 74684fd5ab5..6eeb27a4f6c 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -1,8 +1,8 @@ //! Configs interface +use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; -use storage_impl::errors::ApplicationError; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index 8271e458b24..0ec9411b99d 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -1,3 +1,4 @@ +use error_stack::ResultExt; use router::{ configs::settings::{CmdLineConf, Settings}, core::errors::{ApplicationError, ApplicationResult}, @@ -24,7 +25,8 @@ async fn main() -> ApplicationResult<()> { &conf.log, router_env::service_name!(), [router_env::service_name!(), "actix_server"], - ); + ) + .change_context(ApplicationError::ConfigurationError)?; logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log); @@ -39,8 +41,7 @@ async fn main() -> ApplicationResult<()> { .expect("Failed to create the server"); let _ = server.await; - Err(ApplicationError::from(std::io::Error::new( - std::io::ErrorKind::Other, - "Server shut down", + Err(error_stack::Report::from(ApplicationError::from( + std::io::Error::new(std::io::ErrorKind::Other, "Server shut down"), ))) } diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 1afc09e5a6a..15465d49137 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -116,7 +116,8 @@ pub async fn start_web_server( 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))? + .bind((server.host.as_str(), server.port)) + .change_context(ApplicationError::ConfigurationError)? .workers(server.workers) .run(); let _ = web_server.handle(); diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a29d7e1502d..24143c35024 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -8,6 +8,7 @@ use analytics::{opensearch::OpenSearchConfig, ReportConfig}; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; +use error_stack::ResultExt; #[cfg(feature = "email")] use external_services::email::EmailSettings; use external_services::{ @@ -33,7 +34,7 @@ use storage_impl::config::QueueStrategy; use crate::analytics::AnalyticsConfig; use crate::{ core::errors::{ApplicationError, ApplicationResult}, - env::{self, logger, Env}, + env::{self, Env}, events::EventsConfig, }; @@ -711,7 +712,8 @@ impl Settings<SecuredSecret> { let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); - let config = router_env::Config::builder(&environment.to_string())? + let config = router_env::Config::builder(&environment.to_string()) + .change_context(ApplicationError::ConfigurationError)? .add_source(File::from(config_path).required(false)) .add_source( Environment::with_prefix("ROUTER") @@ -725,13 +727,12 @@ impl Settings<SecuredSecret> { .with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"), ) - .build()?; + .build() + .change_context(ApplicationError::ConfigurationError)?; - serde_path_to_error::deserialize(config).map_err(|error| { - logger::error!(%error, "Unable to deserialize application configuration"); - eprintln!("Unable to deserialize application configuration: {error}"); - ApplicationError::from(error.into_inner()) - }) + serde_path_to_error::deserialize(config) + .attach_printable("Unable to deserialize application configuration") + .change_context(ApplicationError::ConfigurationError) } pub fn validate(&self) -> ApplicationResult<()> { @@ -745,14 +746,18 @@ impl Settings<SecuredSecret> { })?; if self.log.file.enabled { if self.log.file.file_name.is_default_or_empty() { - return Err(ApplicationError::InvalidConfigurationValueError( - "log file name must not be empty".into(), + return Err(error_stack::Report::from( + ApplicationError::InvalidConfigurationValueError( + "log file name must not be empty".into(), + ), )); } if self.log.file.path.is_default_or_empty() { - return Err(ApplicationError::InvalidConfigurationValueError( - "log directory path must not be empty".into(), + return Err(error_stack::Report::from( + ApplicationError::InvalidConfigurationValueError( + "log directory path must not be empty".into(), + ), )); } } diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 83fa2143648..c22465c3a32 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -32,7 +32,7 @@ use crate::services; pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; pub type RouterResponse<T> = CustomResult<services::ApplicationResponse<T>, ApiErrorResponse>; -pub type ApplicationResult<T> = Result<T, ApplicationError>; +pub type ApplicationResult<T> = error_stack::Result<T, ApplicationError>; pub type ApplicationResponse<T> = ApplicationResult<services::ApplicationResponse<T>>; pub type CustomerResponse<T> = diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml index b9b1184fedf..59bfb4d5c8e 100644 --- a/crates/router_env/Cargo.toml +++ b/crates/router_env/Cargo.toml @@ -14,6 +14,7 @@ error-stack = "0.4.1" gethostname = "0.4.3" once_cell = "1.19.0" opentelemetry = { version = "0.19.0", features = ["rt-tokio-current-thread", "metrics"] } +common_enums = { path = "../common_enums" } opentelemetry-otlp = { version = "0.12.0", features = ["metrics"] } rustc-hash = "1.1" serde = { version = "1.0.197", features = ["derive"] } diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs index c14bcf1ba08..6bcf669e73a 100644 --- a/crates/router_env/src/logger/formatter.rs +++ b/crates/router_env/src/logger/formatter.rs @@ -8,6 +8,7 @@ use std::{ io::Write, }; +use config::ConfigError; use once_cell::sync::Lazy; use serde::ser::{SerializeMap, Serializer}; use serde_json::{ser::Formatter, Value}; @@ -155,7 +156,11 @@ where /// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter); /// ``` /// - pub fn new(service: &str, dst_writer: W, formatter: F) -> Self { + pub fn new( + service: &str, + dst_writer: W, + formatter: F, + ) -> error_stack::Result<Self, ConfigError> { Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter) } @@ -163,9 +168,9 @@ where pub fn new_with_implicit_entries( service: &str, dst_writer: W, - mut default_fields: HashMap<String, Value>, + default_fields: HashMap<String, Value>, formatter: F, - ) -> Self { + ) -> error_stack::Result<Self, ConfigError> { let pid = std::process::id(); let hostname = gethostname::gethostname().to_string_lossy().into_owned(); let service = service.to_string(); @@ -174,20 +179,16 @@ where #[cfg(feature = "vergen")] let build = crate::build!().to_string(); let env = crate::env::which().to_string(); - default_fields.retain(|key, value| { - if !IMPLICIT_KEYS.contains(key.as_str()) { - true - } else { - tracing::warn!( - ?key, - ?value, - "Attempting to log a reserved entry. It won't be added to the logs" - ); - false + for key in default_fields.keys() { + if IMPLICIT_KEYS.contains(key.as_str()) { + return Err(ConfigError::Message(format!( + "A reserved key `{key}` was included in `default_fields` in the log formatting layer" + )) + .into()); } - }); + } - Self { + Ok(Self { dst_writer, pid, hostname, @@ -199,7 +200,7 @@ where build, default_fields, formatter, - } + }) } /// Serialize common for both span and event entries. diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index 3a9e719db18..1a936fcebf2 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -2,6 +2,7 @@ use std::time::Duration; +use ::config::ConfigError; use opentelemetry::{ global, runtime, sdk::{ @@ -36,7 +37,7 @@ pub fn setup( config: &config::Log, service_name: &str, crates_to_filter: impl AsRef<[&'static str]>, -) -> TelemetryGuard { +) -> error_stack::Result<TelemetryGuard, ConfigError> { let mut guards = Vec::new(); // Setup OpenTelemetry traces and metrics @@ -69,11 +70,9 @@ pub fn setup( &crates_to_filter, ); println!("Using file logging filter: {file_filter}"); - - Some( - FormattingLayer::new(service_name, file_writer, CompactFormatter) - .with_filter(file_filter), - ) + let layer = FormattingLayer::new(service_name, file_writer, CompactFormatter)? + .with_filter(file_filter); + Some(layer) } else { None }; @@ -107,17 +106,21 @@ pub fn setup( } config::LogFormat::Json => { error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); - let logging_layer = - FormattingLayer::new(service_name, console_writer, CompactFormatter) - .with_filter(console_filter); - subscriber.with(logging_layer).init(); + subscriber + .with( + FormattingLayer::new(service_name, console_writer, CompactFormatter)? + .with_filter(console_filter), + ) + .init(); } config::LogFormat::PrettyJson => { error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); - let logging_layer = - FormattingLayer::new(service_name, console_writer, PrettyFormatter::new()) - .with_filter(console_filter); - subscriber.with(logging_layer).init(); + subscriber + .with( + FormattingLayer::new(service_name, console_writer, PrettyFormatter::new())? + .with_filter(console_filter), + ) + .init(); } } } else { @@ -126,10 +129,10 @@ pub fn setup( // Returning the TelemetryGuard for logs to be printed and metrics to be collected until it is // dropped - TelemetryGuard { + Ok(TelemetryGuard { _log_guards: guards, _metrics_controller, - } + }) } fn get_opentelemetry_exporter(config: &config::LogTelemetry) -> TonicExporterBuilder { diff --git a/crates/router_env/tests/logger.rs b/crates/router_env/tests/logger.rs index 89146619db0..46b5b9538cf 100644 --- a/crates/router_env/tests/logger.rs +++ b/crates/router_env/tests/logger.rs @@ -1,25 +1,25 @@ #![allow(clippy::unwrap_used)] mod test_module; - +use ::config::ConfigError; use router_env::TelemetryGuard; use self::test_module::some_module::*; -fn logger() -> &'static TelemetryGuard { +fn logger() -> error_stack::Result<&'static TelemetryGuard, ConfigError> { use once_cell::sync::OnceCell; static INSTANCE: OnceCell<TelemetryGuard> = OnceCell::new(); - INSTANCE.get_or_init(|| { + Ok(INSTANCE.get_or_init(|| { let config = router_env::Config::new().unwrap(); - router_env::setup(&config.log, "router_env_test", []) - }) + router_env::setup(&config.log, "router_env_test", []).unwrap() + })) } #[tokio::test] async fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { - logger(); + logger()?; fn_with_colon(13).await; diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index ab656c3f658..d96d5ac7d57 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -18,6 +18,7 @@ payouts = ["hyperswitch_domain_models/payouts"] # First Party dependencies api_models = { version = "0.1.0", path = "../api_models" } common_utils = { version = "0.1.0", path = "../common_utils" } +common_enums = { version = "0.1.0", path = "../common_enums" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } diesel_models = { version = "0.1.0", path = "../diesel_models" } masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index b153c47b882..1cee96f49eb 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -1,17 +1,10 @@ -use std::fmt::Display; - -use actix_web::ResponseError; +pub use common_enums::{ApiClientError, ApplicationError, ApplicationResult}; use common_utils::errors::ErrorSwitch; -use config::ConfigError; -use http::StatusCode; use hyperswitch_domain_models::errors::StorageError as DataStorageError; pub use redis_interface::errors::RedisError; -use router_env::opentelemetry::metrics::MetricsError; use crate::store::errors::DatabaseError; -pub type ApplicationResult<T> = Result<T, ApplicationError>; - #[derive(Debug, thiserror::Error)] pub enum StorageError { #[error("DatabaseError: {0:?}")] @@ -154,115 +147,6 @@ impl RedisErrorExt for error_stack::Report<RedisError> { } } -#[derive(Debug, thiserror::Error)] -pub enum ApplicationError { - // Display's impl can be overridden by the attribute error marco. - // Don't use Debug here, Debug gives error stack in response. - #[error("Application configuration error: {0}")] - ConfigurationError(ConfigError), - - #[error("Invalid configuration value provided: {0}")] - InvalidConfigurationValueError(String), - - #[error("Metrics error: {0}")] - MetricsError(MetricsError), - - #[error("I/O: {0}")] - IoError(std::io::Error), - - #[error("Error while constructing api client: {0}")] - ApiClientError(ApiClientError), -} - -impl From<MetricsError> for ApplicationError { - fn from(err: MetricsError) -> Self { - Self::MetricsError(err) - } -} - -impl From<std::io::Error> for ApplicationError { - fn from(err: std::io::Error) -> Self { - Self::IoError(err) - } -} - -impl From<ConfigError> for ApplicationError { - fn from(err: ConfigError) -> Self { - Self::ConfigurationError(err) - } -} - -fn error_response<T: Display>(err: &T) -> actix_web::HttpResponse { - actix_web::HttpResponse::BadRequest() - .content_type(mime::APPLICATION_JSON) - .body(format!(r#"{{ "error": {{ "message": "{err}" }} }}"#)) -} - -impl ResponseError for ApplicationError { - fn status_code(&self) -> StatusCode { - match self { - Self::MetricsError(_) - | Self::IoError(_) - | Self::ConfigurationError(_) - | Self::InvalidConfigurationValueError(_) - | Self::ApiClientError(_) => StatusCode::INTERNAL_SERVER_ERROR, - } - } - - fn error_response(&self) -> actix_web::HttpResponse { - error_response(self) - } -} - -#[derive(Debug, thiserror::Error, PartialEq, Clone)] -pub enum ApiClientError { - #[error("Header map construction failed")] - HeaderMapConstructionFailed, - #[error("Invalid proxy configuration")] - InvalidProxyConfiguration, - #[error("Client construction failed")] - ClientConstructionFailed, - #[error("Certificate decode failed")] - CertificateDecodeFailed, - #[error("Request body serialization failed")] - BodySerializationFailed, - #[error("Unexpected state reached/Invariants conflicted")] - UnexpectedState, - - #[error("URL encoding of request payload failed")] - UrlEncodingFailed, - #[error("Failed to send request to connector {0}")] - RequestNotSent(String), - #[error("Failed to decode response")] - ResponseDecodingFailed, - - #[error("Server responded with Request Timeout")] - RequestTimeoutReceived, - - #[error("connection closed before a message could complete")] - ConnectionClosedIncompleteMessage, - - #[error("Server responded with Internal Server Error")] - InternalServerErrorReceived, - #[error("Server responded with Bad Gateway")] - BadGatewayReceived, - #[error("Server responded with Service Unavailable")] - ServiceUnavailableReceived, - #[error("Server responded with Gateway Timeout")] - GatewayTimeoutReceived, - #[error("Server responded with unexpected response")] - UnexpectedServerResponse, -} - -impl ApiClientError { - pub fn is_upstream_timeout(&self) -> bool { - self == &Self::RequestTimeoutReceived - } - pub fn is_connection_closed_before_message_could_complete(&self) -> bool { - self == &Self::ConnectionClosedIncompleteMessage - } -} - #[derive(Debug, thiserror::Error, PartialEq)] pub enum ConnectorError { #[error("Error while obtaining URL for the integration")]
2024-07-03T08:46:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Emit a setup error when a restricted keys are used for logging default keys ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? <img width="1728" alt="image" src="https://github.com/juspay/hyperswitch/assets/89402434/51cdce91-e6a9-4fc1-8ba0-8b9b309cffc9"> --> Enable the `level = "TRACE"` and `log_format = "pretty_json"` in development.toml and `cargo run` it will show the logs ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
35d502e3da6b271452011dfae178108e3ba8c3c7
juspay/hyperswitch
juspay__hyperswitch-5009
Bug: Include the pre-routing connectors in apple pay retries Currently for apple pay pre-routing is done before the session call and only one connector is decided based on the routing logic. Now since we want to enable auto retries for apple pay we need to consider all the connectors form the routing rule and construct a list of it. After which this connectors should be filtered out with the connectors that supports apple pay simplified flow. Once this is done there will be a list of connectors with which apple pay retries can we performed.
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 66a695b2b0c..1ecc7a231ce 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2014,7 +2014,15 @@ pub async fn list_payment_methods( } if let Some(choice) = result.get(&intermediate.payment_method_type) { - intermediate.connector == choice.connector.connector_name.to_string() + if let Some(first_routable_connector) = choice.first() { + intermediate.connector + == first_routable_connector + .connector + .connector_name + .to_string() + } else { + false + } } else { false } @@ -2034,26 +2042,32 @@ pub async fn list_payment_methods( let mut pre_routing_results: HashMap< api_enums::PaymentMethodType, - routing_types::RoutableConnectorChoice, + storage::PreRoutingConnectorChoice, > = HashMap::new(); - for (pm_type, choice) in result { - let routable_choice = routing_types::RoutableConnectorChoice { - #[cfg(feature = "backwards_compatibility")] - choice_kind: routing_types::RoutableChoiceKind::FullStruct, - connector: choice - .connector - .connector_name - .to_string() - .parse::<api_enums::RoutableConnectors>() - .change_context(errors::ApiErrorResponse::InternalServerError)?, - #[cfg(feature = "connector_choice_mca_id")] - merchant_connector_id: choice.connector.merchant_connector_id, - #[cfg(not(feature = "connector_choice_mca_id"))] - sub_label: choice.sub_label, - }; - - pre_routing_results.insert(pm_type, routable_choice); + for (pm_type, routing_choice) in result { + let mut routable_choice_list = vec![]; + for choice in routing_choice { + let routable_choice = routing_types::RoutableConnectorChoice { + #[cfg(feature = "backwards_compatibility")] + choice_kind: routing_types::RoutableChoiceKind::FullStruct, + connector: choice + .connector + .connector_name + .to_string() + .parse::<api_enums::RoutableConnectors>() + .change_context(errors::ApiErrorResponse::InternalServerError)?, + #[cfg(feature = "connector_choice_mca_id")] + merchant_connector_id: choice.connector.merchant_connector_id.clone(), + #[cfg(not(feature = "connector_choice_mca_id"))] + sub_label: choice.sub_label, + }; + routable_choice_list.push(routable_choice); + } + pre_routing_results.insert( + pm_type, + storage::PreRoutingConnectorChoice::Multiple(routable_choice_list), + ); } let redis_conn = db @@ -2064,15 +2078,28 @@ pub async fn list_payment_methods( let mut val = Vec::new(); for (payment_method_type, routable_connector_choice) in &pre_routing_results { + let routable_connector_list = match routable_connector_choice { + storage::PreRoutingConnectorChoice::Single(routable_connector) => { + vec![routable_connector.clone()] + } + storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + routable_connector_list.clone() + } + }; + + let first_routable_connector = routable_connector_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; + #[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(), + first_routable_connector.sub_label.as_ref(), #[cfg(feature = "connector_choice_mca_id")] None, - routable_connector_choice.connector.to_string().as_str(), + first_routable_connector.connector.to_string().as_str(), ); #[cfg(not(feature = "connector_choice_mca_id"))] let matched_mca = filtered_mcas @@ -2081,7 +2108,7 @@ pub async fn list_payment_methods( #[cfg(feature = "connector_choice_mca_id")] let matched_mca = filtered_mcas.iter().find(|m| { - routable_connector_choice.merchant_connector_id.as_ref() + first_routable_connector.merchant_connector_id.as_ref() == Some(&m.merchant_connector_id) }); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7bc0b532239..c8ae3f7d872 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3137,39 +3137,58 @@ where .as_ref() .zip(payment_data.payment_attempt.payment_method_type.as_ref()) { - if let (Some(choice), None) = ( + if let (Some(routable_connector_choice), None) = ( pre_routing_results.get(storage_pm_type), &payment_data.token_data, ) { - let connector_data = api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - &choice.connector.to_string(), - api::GetToken::Connector, - #[cfg(feature = "connector_choice_mca_id")] - choice.merchant_connector_id.clone(), - #[cfg(not(feature = "connector_choice_mca_id"))] - None, - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; + let routable_connector_list = match routable_connector_choice { + storage::PreRoutingConnectorChoice::Single(routable_connector) => { + vec![routable_connector.clone()] + } + storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + routable_connector_list.clone() + } + }; + + let mut pre_routing_connector_data_list = vec![]; - routing_data.routed_through = Some(choice.connector.to_string()); + let first_routable_connector = routable_connector_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; + + routing_data.routed_through = Some(first_routable_connector.connector.to_string()); #[cfg(feature = "connector_choice_mca_id")] { routing_data .merchant_connector_id - .clone_from(&choice.merchant_connector_id); + .clone_from(&first_routable_connector.merchant_connector_id); } #[cfg(not(feature = "connector_choice_mca_id"))] { - routing_data.business_sub_label = choice.sub_label.clone(); + routing_data.business_sub_label = first_routable_connector.sub_label.clone(); + } + + for connector_choice in routable_connector_list.clone() { + let connector_data = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_choice.connector.to_string(), + api::GetToken::Connector, + #[cfg(feature = "connector_choice_mca_id")] + connector_choice.merchant_connector_id.clone(), + #[cfg(not(feature = "connector_choice_mca_id"))] + None, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")?; + + pre_routing_connector_data_list.push(connector_data); } - #[cfg(feature = "retry")] + #[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))] let should_do_retry = retry::config_should_call_gsm(&*state.store, &merchant_account.merchant_id).await; - #[cfg(feature = "retry")] + #[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))] if payment_data.payment_attempt.payment_method_type == Some(storage_enums::PaymentMethodType::ApplePay) && should_do_retry @@ -3179,20 +3198,29 @@ where merchant_account, payment_data, key_store, - connector_data.clone(), - #[cfg(feature = "connector_choice_mca_id")] - choice.merchant_connector_id.clone().as_ref(), - #[cfg(not(feature = "connector_choice_mca_id"))] - None, + &pre_routing_connector_data_list, + first_routable_connector + .merchant_connector_id + .clone() + .as_ref(), ) .await?; if let Some(connector_data_list) = retryable_connector_data { - return Ok(ConnectorCallType::Retryable(connector_data_list)); + if connector_data_list.len() > 1 { + logger::info!("Constructed apple pay retryable connector list"); + return Ok(ConnectorCallType::Retryable(connector_data_list)); + } } } - return Ok(ConnectorCallType::PreDetermined(connector_data)); + let first_pre_routing_connector_data_list = pre_routing_connector_data_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; + + return Ok(ConnectorCallType::PreDetermined( + first_pre_routing_connector_data_list.clone(), + )); } } @@ -3569,11 +3597,22 @@ where })); let mut final_list: Vec<api::SessionConnectorData> = Vec::new(); - for (routed_pm_type, choice) in pre_routing_results.into_iter() { - if let Some(session_connector_data) = - payment_methods.remove(&(choice.to_string(), routed_pm_type)) - { - final_list.push(session_connector_data); + for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() { + let routable_connector_list = match pre_routing_choice { + storage::PreRoutingConnectorChoice::Single(routable_connector) => { + vec![routable_connector.clone()] + } + storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + routable_connector_list.clone() + } + }; + for routable_connector in routable_connector_list { + if let Some(session_connector_data) = + payment_methods.remove(&(routable_connector.to_string(), routed_pm_type)) + { + final_list.push(session_connector_data); + break; + } } } @@ -3621,8 +3660,11 @@ where if !routing_enabled_pms.contains(&connector_data.payment_method_type) { final_list.push(connector_data); } else if let Some(choice) = result.get(&connector_data.payment_method_type) { - if connector_data.connector.connector_name == choice.connector.connector_name { - connector_data.business_sub_label = choice.sub_label.clone(); + let routing_choice = choice + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + if connector_data.connector.connector_name == routing_choice.connector.connector_name { + connector_data.business_sub_label = routing_choice.sub_label.clone(); final_list.push(connector_data); } } @@ -3633,7 +3675,10 @@ where if !routing_enabled_pms.contains(&connector_data.payment_method_type) { final_list.push(connector_data); } else if let Some(choice) = result.get(&connector_data.payment_method_type) { - if connector_data.connector.connector_name == choice.connector.connector_name { + let routing_choice = choice + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + if connector_data.connector.connector_name == routing_choice.connector.connector_name { final_list.push(connector_data); } } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 8f7ed4da256..5bbed873103 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3961,12 +3961,13 @@ pub fn get_applepay_metadata( }) } +#[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))] pub async fn get_apple_pay_retryable_connectors<F>( state: AppState, merchant_account: &domain::MerchantAccount, payment_data: &mut PaymentData<F>, key_store: &domain::MerchantKeyStore, - decided_connector_data: api::ConnectorData, + pre_routing_connector_data_list: &[api::ConnectorData], merchant_connector_id: Option<&String>, ) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse> where @@ -3981,13 +3982,17 @@ where field_name: "profile_id", })?; + let pre_decided_connector_data_first = pre_routing_connector_data_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; + let merchant_connector_account_type = get_merchant_connector_account( &state, merchant_account.merchant_id.as_str(), payment_data.creds_identifier.to_owned(), key_store, - profile_id, // need to fix this - &decided_connector_data.connector_name.to_string(), + profile_id, + &pre_decided_connector_data_first.connector_name.to_string(), merchant_connector_id, ) .await?; @@ -4008,9 +4013,14 @@ where .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; - let mut connector_data_list = vec![decided_connector_data.clone()]; + let profile_specific_merchant_connector_account_list = filter_mca_based_on_business_profile( + merchant_connector_account_list, + Some(profile_id.to_string()), + ); + + let mut connector_data_list = vec![pre_decided_connector_data_first.clone()]; - for merchant_connector_account in merchant_connector_account_list { + for merchant_connector_account in profile_specific_merchant_connector_account_list { if is_apple_pay_simplified_flow( merchant_connector_account.metadata, Some(&merchant_connector_account.connector_name), @@ -4031,7 +4041,48 @@ where } } } - Some(connector_data_list) + + let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config( + &*state.clone().store, + profile_id, + &api_enums::TransactionType::Payment, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get merchant default fallback connectors config")?; + + let mut routing_connector_data_list = Vec::new(); + + pre_routing_connector_data_list.iter().for_each(|pre_val| { + routing_connector_data_list.push(pre_val.merchant_connector_id.clone()) + }); + + fallback_connetors_list.iter().for_each(|fallback_val| { + routing_connector_data_list + .iter() + .all(|val| *val != fallback_val.merchant_connector_id) + .then(|| { + routing_connector_data_list.push(fallback_val.merchant_connector_id.clone()) + }); + }); + + // connector_data_list is the list of connectors for which Apple Pay simplified flow is configured. + // This list is arranged in the same order as the merchant's connectors routingconfiguration. + + let mut ordered_connector_data_list = Vec::new(); + + routing_connector_data_list + .iter() + .for_each(|merchant_connector_id| { + let connector_data = connector_data_list.iter().find(|connector_data| { + *merchant_connector_id == connector_data.merchant_connector_id + }); + if let Some(connector_data_details) = connector_data { + ordered_connector_data_list.push(connector_data_details.clone()); + } + }); + + Some(ordered_connector_data_list) } else { None }; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index d45f804268b..320f326275e 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -832,7 +832,8 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>( pub async fn perform_session_flow_routing( session_input: SessionFlowRoutingInput<'_>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice>> { +) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>> +{ let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> = FxHashMap::default(); @@ -939,8 +940,10 @@ pub async fn perform_session_flow_routing( ); } - let mut result: FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice> = - FxHashMap::default(); + let mut result: FxHashMap< + api_enums::PaymentMethodType, + Vec<routing_types::SessionRoutingChoice>, + > = FxHashMap::default(); for (pm_type, allowed_connectors) in pm_type_map { let euclid_pmt: euclid_enums::PaymentMethodType = pm_type; @@ -962,20 +965,37 @@ pub async fn perform_session_flow_routing( ))] profile_id: session_input.payment_intent.profile_id.clone(), }; - let maybe_choice = - perform_session_routing_for_pm_type(session_pm_input, transaction_type).await?; - - // (connector, sub_label) - if let Some(data) = maybe_choice { - result.insert( - pm_type, - routing_types::SessionRoutingChoice { - connector: data.0, + let routable_connector_choice_option = + perform_session_routing_for_pm_type(&session_pm_input, transaction_type).await?; + + if let Some(routable_connector_choice) = routable_connector_choice_option { + let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new(); + + for selection in routable_connector_choice { + let connector_name = selection.connector.to_string(); + if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) { + let connector_data = api::ConnectorData::get_connector_by_name( + &session_pm_input.state.clone().conf.connectors, + &connector_name, + get_token.clone(), + #[cfg(feature = "connector_choice_mca_id")] + selection.merchant_connector_id, + #[cfg(not(feature = "connector_choice_mca_id"))] + None, + ) + .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?; #[cfg(not(feature = "connector_choice_mca_id"))] - sub_label: data.1, - payment_method_type: pm_type, - }, - ); + let sub_label = selection.sub_label; + + session_routing_choice.push(routing_types::SessionRoutingChoice { + connector: connector_data, + #[cfg(not(feature = "connector_choice_mca_id"))] + sub_label: sub_label, + payment_method_type: pm_type, + }); + } + } + result.insert(pm_type, session_routing_choice); } } @@ -983,9 +1003,9 @@ pub async fn perform_session_flow_routing( } async fn perform_session_routing_for_pm_type( - session_pm_input: SessionRoutingPmTypeInput<'_>, + session_pm_input: &SessionRoutingPmTypeInput<'_>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<Option<(api::ConnectorData, Option<String>)>> { +) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> { let merchant_id = &session_pm_input.key_store.merchant_id; let chosen_connectors = match session_pm_input.routing_algorithm { @@ -1068,7 +1088,7 @@ async fn perform_session_routing_for_pm_type( &session_pm_input.state.clone(), session_pm_input.key_store, fallback, - session_pm_input.backend_input, + session_pm_input.backend_input.clone(), None, #[cfg(feature = "business_profile_routing")] session_pm_input.profile_id.clone(), @@ -1077,32 +1097,11 @@ async fn perform_session_routing_for_pm_type( .await?; } - let mut final_choice: Option<(api::ConnectorData, Option<String>)> = None; - - for selection in final_selection { - let connector_name = selection.connector.to_string(); - if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) { - let connector_data = api::ConnectorData::get_connector_by_name( - &session_pm_input.state.clone().conf.connectors, - &connector_name, - get_token.clone(), - #[cfg(feature = "connector_choice_mca_id")] - selection.merchant_connector_id, - #[cfg(not(feature = "connector_choice_mca_id"))] - None, - ) - .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?; - #[cfg(not(feature = "connector_choice_mca_id"))] - let sub_label = selection.sub_label; - #[cfg(feature = "connector_choice_mca_id")] - let sub_label = None; - - final_choice = Some((connector_data, sub_label)); - break; - } + if final_selection.is_empty() { + Ok(None) + } else { + Ok(Some(final_selection)) } - - Ok(final_choice) } pub fn make_dsl_input_for_surcharge( diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 77550bedabe..79c8b2ed2f0 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -81,14 +81,21 @@ pub struct RoutingData { pub struct PaymentRoutingInfo { pub algorithm: Option<routing::StraightThroughAlgorithm>, pub pre_routing_results: - Option<HashMap<api_models::enums::PaymentMethodType, routing::RoutableConnectorChoice>>, + Option<HashMap<api_models::enums::PaymentMethodType, PreRoutingConnectorChoice>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRoutingInfoInner { pub algorithm: Option<routing::StraightThroughAlgorithm>, pub pre_routing_results: - Option<HashMap<api_models::enums::PaymentMethodType, routing::RoutableConnectorChoice>>, + Option<HashMap<api_models::enums::PaymentMethodType, PreRoutingConnectorChoice>>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum PreRoutingConnectorChoice { + Single(routing::RoutableConnectorChoice), + Multiple(Vec<routing::RoutableConnectorChoice>), } #[derive(Debug, serde::Serialize, serde::Deserialize)]
2024-06-14T06:45:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently for apple pay pre-routing is done before the session call and only one connector is decided based on the routing logic. Now since we want to enable auto retries for apple pay we need to consider all the connectors form the routing rule and construct a list of it. After which this connectors should be filtered out with the connectors that supports apple pay simplified flow. Once this is done there will be a list of connectors with which apple pay retries can we performed. Corresponding pr on the main branch https://github.com/juspay/hyperswitch/pull/4952 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant account -> Enable auto retries for the specific `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "should_call_gsm_merchant_1718202727", "value": "true" }' ``` -> Set the maximum retry counts for the auto retries enabled `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "max_auto_retries_enabled_merchant_1718202727", "value": "1" }' ``` -> Configure the error code and error message in the gsm ``` curl --location 'localhost:8080/gsm' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "connector": "stripe", "flow": "Authorize", "sub_flow": "sub_flow", "code": "No error code", "message": "No error message", "status": "Failure", "decision": "retry", "step_up_possible": false }' ``` -> Create merchant connector accounts (enable apple pay simplified if you wish to retry the failed apple pay payment with it) metadata for simplified flow ``` "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Configure the routing rules for the configured connectors ``` curl --location 'http://localhost:8080/routing' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \ --data '{ "name": "priority config", "description": "some desc", "algorithm": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_eF7yV3fNcAZ2wmGlKORq" }, { "connector": "cybersource", "merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj" }, { "connector": "adyen", "merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU" }, { "connector": "rapyd", "merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq" } ] }, "profile_id": "pro_Rv8QaYCARaEOCglUGXpa" }' ``` <img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0fc7248d-abcb-487f-b266-afa98b28b2d6"> -> Create a apple pay payment with confirm false ``` { "amount": 6500, "currency": "USD", "confirm": false, "amount_to_capture": 6500, "customer_id": "test_priority_routing", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "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" } } } ``` <img width="1167" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/58e46427-c1ea-4ef0-a8d9-5c2012e7f694"> -> List payment methods for merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_uKquqDLCGBBzbXpsEKyy_secret_soCWAMLK8xCq7WZ42KQD' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_97bb28e2fc3b42099d802df96188f7ec' ``` <img width="1058" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/dea9b073-52db-43f5-9eff-b5c760b1d9ab"> -> Confirm the payment with the `payment_id` ``` curl --location 'http://localhost:8080/payments/pay_MwqtOPwRf05n4A99hvBI/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "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" }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01XpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1067" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e6f20fca-0da9-47f5-a84d-0e61f30dea25"> -> Retrieve payment attempt ``` curl --location 'http://localhost:8080/payments/pay_MwqtOPwRf05n4A99hvBI?expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' ``` <img width="1148" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/330a6b37-0b51-4f2e-a525-3fc8a333487e"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
bf239131572f488d5393e9fa932f9987751e0cbc
juspay/hyperswitch
juspay__hyperswitch-5008
Bug: [FEATURE] Inclusion of customer details in payment_intent column ### Feature Description This change will insure storage of customer_details in our payment_intent table. Which will help us to derive the customer_details directly in one db call. ### Possible Implementation if customer_id alone is passed -> Derive customer_details from customer_table and put it in guest_customer_details, if customer_id is not present -> Put the details in guest_customer_details. if both are present -> we are ignoring the email, phone etc and deriving them from customer_table and adding to the guest_customer_details field. ### 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 bf275a0dd0f..d477142fe82 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -202,11 +202,11 @@ pub struct CustomerDetails { pub phone_country_code: Option<String>, } -#[derive(Debug, serde::Serialize, Clone, ToSchema, PartialEq)] +#[derive(Debug, Default, serde::Serialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The identifier for the customer. - #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] - pub id: id_type::CustomerId, + #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] + pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 6326eeef646..fa37eecdbfe 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -4,9 +4,9 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums as storage_enums, schema::payment_intent}; +use crate::{encryption::Encryption, enums as storage_enums, schema::payment_intent}; -#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id))] pub struct PaymentIntent { pub payment_id: String, @@ -59,10 +59,11 @@ pub struct PaymentIntent { pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, + pub customer_details: Option<Encryption>, } #[derive( - Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, + Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { @@ -114,6 +115,7 @@ pub struct PaymentIntentNew { pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, + pub customer_details: Option<Encryption>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -130,12 +132,13 @@ pub enum PaymentIntentUpdate { metadata: pii::SecretSerdeValue, updated_by: String, }, - ReturnUrlUpdate { + PaymentCreateUpdate { return_url: Option<String>, status: Option<storage_enums::IntentStatus>, customer_id: Option<id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, + customer_details: Option<Encryption>, updated_by: String, }, MerchantStatusUpdate { @@ -171,6 +174,7 @@ pub enum PaymentIntentUpdate { fingerprint_id: Option<String>, request_external_three_ds_authentication: Option<bool>, frm_metadata: Option<pii::SecretSerdeValue>, + customer_details: Option<Encryption>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, @@ -246,6 +250,7 @@ pub struct PaymentIntentUpdateInternal { pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, + pub customer_details: Option<Encryption>, } impl PaymentIntentUpdate { @@ -281,6 +286,7 @@ impl PaymentIntentUpdate { fingerprint_id, request_external_three_ds_authentication, frm_metadata, + customer_details, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), @@ -318,6 +324,7 @@ impl PaymentIntentUpdate { request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), frm_metadata: frm_metadata.or(source.frm_metadata), + customer_details: customer_details.or(source.customer_details), ..source } } @@ -348,6 +355,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fingerprint_id, request_external_three_ds_authentication, frm_metadata, + customer_details, } => Self { amount: Some(amount), currency: Some(currency), @@ -371,6 +379,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fingerprint_id, request_external_three_ds_authentication, frm_metadata, + customer_details, ..Default::default() }, PaymentIntentUpdate::MetadataUpdate { @@ -382,12 +391,13 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { updated_by, ..Default::default() }, - PaymentIntentUpdate::ReturnUrlUpdate { + PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, + customer_details, updated_by, } => Self { return_url, @@ -395,6 +405,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { customer_id, shipping_address_id, billing_address_id, + customer_details, modified_at: Some(common_utils::date_time::now()), updated_by, ..Default::default() diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 162dac1377e..6149af1f505 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -888,6 +888,7 @@ diesel::table! { request_external_three_ds_authentication -> Nullable<Bool>, charges -> Nullable<Jsonb>, frm_metadata -> Nullable<Jsonb>, + customer_details -> Nullable<Bytea>, } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index c09df82f87c..f6e4f888790 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -1,4 +1,5 @@ -use common_utils::{self, id_type, pii, types::MinorUnit}; +use common_utils::{self, crypto::Encryptable, id_type, pii, types::MinorUnit}; +use masking::Secret; use time::PrimitiveDateTime; pub mod payment_attempt; @@ -9,7 +10,7 @@ use common_enums as storage_enums; use self::payment_attempt::PaymentAttempt; use crate::RemoteStorageObject; -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] +#[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct PaymentIntent { pub payment_id: String, pub merchant_id: String, @@ -61,4 +62,5 @@ pub struct PaymentIntent { pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, + pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 4f50948b480..1dca50e6482 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -4,6 +4,8 @@ use common_utils::{ errors::{CustomResult, ValidationError}, types::MinorUnit, }; +use error_stack::ResultExt; +use masking::PeekInterface; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -11,6 +13,7 @@ use super::PaymentIntent; use crate::{ behaviour, errors, mandates::{MandateDataType, MandateDetails}, + type_encryption::{decrypt, AsyncLift}, ForeignIDRef, RemoteStorageObject, }; @@ -472,7 +475,8 @@ impl ForeignIDRef for PaymentAttempt { } use diesel_models::{ - PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, + encryption::Encryption, PaymentIntent as DieselPaymentIntent, + PaymentIntentNew as DieselPaymentIntentNew, }; #[async_trait::async_trait] @@ -525,61 +529,73 @@ impl behaviour::Conversion for PaymentIntent { request_external_three_ds_authentication: self.request_external_three_ds_authentication, charges: self.charges, frm_metadata: self.frm_metadata, + customer_details: self.customer_details.map(Encryption::from), }) } async fn convert_back( storage_model: Self::DstType, - _key: &masking::Secret<Vec<u8>>, + key: &masking::Secret<Vec<u8>>, ) -> CustomResult<Self, ValidationError> where Self: Sized, { - Ok(Self { - payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, - status: storage_model.status, - amount: storage_model.amount, - currency: storage_model.currency, - amount_captured: storage_model.amount_captured, - customer_id: storage_model.customer_id, - description: storage_model.description, - return_url: storage_model.return_url, - metadata: storage_model.metadata, - connector_id: storage_model.connector_id, - shipping_address_id: storage_model.shipping_address_id, - billing_address_id: storage_model.billing_address_id, - statement_descriptor_name: storage_model.statement_descriptor_name, - statement_descriptor_suffix: storage_model.statement_descriptor_suffix, - created_at: storage_model.created_at, - modified_at: storage_model.modified_at, - last_synced: storage_model.last_synced, - setup_future_usage: storage_model.setup_future_usage, - off_session: storage_model.off_session, - client_secret: storage_model.client_secret, - active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id), - business_country: storage_model.business_country, - business_label: storage_model.business_label, - order_details: storage_model.order_details, - allowed_payment_method_types: storage_model.allowed_payment_method_types, - connector_metadata: storage_model.connector_metadata, - feature_metadata: storage_model.feature_metadata, - attempt_count: storage_model.attempt_count, - profile_id: storage_model.profile_id, - merchant_decision: storage_model.merchant_decision, - payment_link_id: storage_model.payment_link_id, - payment_confirm_source: storage_model.payment_confirm_source, - updated_by: storage_model.updated_by, - surcharge_applicable: storage_model.surcharge_applicable, - 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, - request_external_three_ds_authentication: storage_model - .request_external_three_ds_authentication, - charges: storage_model.charges, - frm_metadata: storage_model.frm_metadata, + async { + let inner_decrypt = |inner| decrypt(inner, key.peek()); + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { + payment_id: storage_model.payment_id, + merchant_id: storage_model.merchant_id, + status: storage_model.status, + amount: storage_model.amount, + currency: storage_model.currency, + amount_captured: storage_model.amount_captured, + customer_id: storage_model.customer_id, + description: storage_model.description, + return_url: storage_model.return_url, + metadata: storage_model.metadata, + connector_id: storage_model.connector_id, + shipping_address_id: storage_model.shipping_address_id, + billing_address_id: storage_model.billing_address_id, + statement_descriptor_name: storage_model.statement_descriptor_name, + statement_descriptor_suffix: storage_model.statement_descriptor_suffix, + created_at: storage_model.created_at, + modified_at: storage_model.modified_at, + last_synced: storage_model.last_synced, + setup_future_usage: storage_model.setup_future_usage, + off_session: storage_model.off_session, + client_secret: storage_model.client_secret, + active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id), + business_country: storage_model.business_country, + business_label: storage_model.business_label, + order_details: storage_model.order_details, + allowed_payment_method_types: storage_model.allowed_payment_method_types, + connector_metadata: storage_model.connector_metadata, + feature_metadata: storage_model.feature_metadata, + attempt_count: storage_model.attempt_count, + profile_id: storage_model.profile_id, + merchant_decision: storage_model.merchant_decision, + payment_link_id: storage_model.payment_link_id, + payment_confirm_source: storage_model.payment_confirm_source, + updated_by: storage_model.updated_by, + surcharge_applicable: storage_model.surcharge_applicable, + 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, + request_external_three_ds_authentication: storage_model + .request_external_three_ds_authentication, + charges: storage_model.charges, + frm_metadata: storage_model.frm_metadata, + customer_details: storage_model + .customer_details + .async_lift(inner_decrypt) + .await?, + }) + } + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting payment intent".to_string(), }) } @@ -628,6 +644,7 @@ impl behaviour::Conversion for PaymentIntent { request_external_three_ds_authentication: self.request_external_three_ds_authentication, charges: self.charges, frm_metadata: self.frm_metadata, + customer_details: self.customer_details.map(Encryption::from), }) } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 66ecf7ec57f..30fd1061c7f 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1,10 +1,13 @@ use common_enums as storage_enums; use common_utils::{ consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, - id_type, pii, + crypto::Encryptable, + id_type, + pii::{self, Email}, types::MinorUnit, }; -use serde::{Deserialize, Serialize}; +use masking::{Deserialize, Secret}; +use serde::Serialize; use time::PrimitiveDateTime; use super::{payment_attempt::PaymentAttempt, PaymentIntent}; @@ -76,7 +79,15 @@ pub trait PaymentIntentInterface { ) -> error_stack::Result<Vec<String>, errors::StorageError>; } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, PartialEq, router_derive::DebugAsDisplay, Serialize, Deserialize)] +pub struct CustomerData { + pub name: Option<Secret<String>>, + pub email: Option<Email>, + pub phone: Option<Secret<String>>, + pub phone_country_code: Option<String>, +} + +#[derive(Clone, Debug, PartialEq)] pub struct PaymentIntentNew { pub payment_id: String, pub merchant_id: String, @@ -122,9 +133,10 @@ pub struct PaymentIntentNew { pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, + pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize)] pub enum PaymentIntentUpdate { ResponseUpdate { status: storage_enums::IntentStatus, @@ -138,12 +150,13 @@ pub enum PaymentIntentUpdate { metadata: pii::SecretSerdeValue, updated_by: String, }, - ReturnUrlUpdate { + PaymentCreateUpdate { return_url: Option<String>, status: Option<storage_enums::IntentStatus>, customer_id: Option<id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, + customer_details: Option<Encryptable<Secret<serde_json::Value>>>, updated_by: String, }, MerchantStatusUpdate { @@ -179,6 +192,7 @@ pub enum PaymentIntentUpdate { fingerprint_id: Option<String>, session_expiry: Option<PrimitiveDateTime>, request_external_three_ds_authentication: Option<bool>, + customer_details: Option<Encryptable<Secret<serde_json::Value>>>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, @@ -255,6 +269,7 @@ pub struct PaymentIntentUpdateInternal { pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, + pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, } impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { @@ -282,6 +297,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { session_expiry, request_external_three_ds_authentication, frm_metadata, + customer_details, } => Self { amount: Some(amount), currency: Some(currency), @@ -305,6 +321,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { session_expiry, request_external_three_ds_authentication, frm_metadata, + customer_details, ..Default::default() }, PaymentIntentUpdate::MetadataUpdate { @@ -316,12 +333,13 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { updated_by, ..Default::default() }, - PaymentIntentUpdate::ReturnUrlUpdate { + PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, + customer_details, updated_by, } => Self { return_url, @@ -329,6 +347,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { customer_id, shipping_address_id, billing_address_id, + customer_details, modified_at: Some(common_utils::date_time::now()), updated_by, ..Default::default() @@ -456,7 +475,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { } } -use diesel_models::PaymentIntentUpdate as DieselPaymentIntentUpdate; +use diesel_models::{encryption::Encryption, PaymentIntentUpdate as DieselPaymentIntentUpdate}; impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { fn from(value: PaymentIntentUpdate) -> Self { @@ -483,19 +502,21 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { metadata, updated_by, }, - PaymentIntentUpdate::ReturnUrlUpdate { + PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, + customer_details, updated_by, - } => Self::ReturnUrlUpdate { + } => Self::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, + customer_details: customer_details.map(Encryption::from), updated_by, }, PaymentIntentUpdate::MerchantStatusUpdate { @@ -540,6 +561,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { session_expiry, request_external_three_ds_authentication, frm_metadata, + customer_details, } => Self::Update { amount, currency, @@ -562,6 +584,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { session_expiry, request_external_three_ds_authentication, frm_metadata, + customer_details: customer_details.map(Encryption::from), }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, @@ -663,6 +686,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt fingerprint_id, request_external_three_ds_authentication, frm_metadata, + customer_details, } = value; Self { @@ -696,6 +720,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt fingerprint_id, request_external_three_ds_authentication, frm_metadata, + customer_details: customer_details.map(Encryption::from), } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 53b0063c6ef..489cbe53c5c 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -22,6 +22,7 @@ use api_models::{ use common_enums::enums::MerchantStorageScheme; use common_utils::{ consts, + crypto::Encryptable, ext_traits::{AsyncExt, Encode, StringExt, ValueExt}, generate_id, id_type, }; @@ -65,7 +66,7 @@ use crate::{ types::{decrypt, encrypt_optional, AsyncLift}, }, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, - transformers::ForeignFrom, + transformers::{ForeignFrom, ForeignTryFrom}, }, utils::{self, ConnectorResponseExt, OptionExt}, }; @@ -466,8 +467,9 @@ pub async fn add_payment_method_data( }; let updated_pmd = Some(PaymentMethodsData::Card(updated_card)); - let pm_data_encrypted = - create_encrypted_data(&key_store, updated_pmd).await; + let pm_data_encrypted = create_encrypted_data(&key_store, updated_pmd) + .await + .map(|details| details.into()); let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate { payment_method_data: pm_data_encrypted, @@ -688,7 +690,9 @@ pub async fn add_payment_method( let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) }); - let pm_data_encrypted = create_encrypted_data(key_store, updated_pmd).await; + let pm_data_encrypted = create_encrypted_data(key_store, updated_pmd) + .await + .map(|details| details.into()); let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: pm_data_encrypted, @@ -762,7 +766,10 @@ pub async fn insert_payment_method( .card .as_ref() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); - let pm_data_encrypted = create_encrypted_data(key_store, pm_card_details).await; + let pm_data_encrypted = create_encrypted_data(key_store, pm_card_details) + .await + .map(|details| details.into()); + create_payment_method( db, &req, @@ -942,7 +949,9 @@ pub async fn update_customer_payment_method( let updated_pmd = updated_card .as_ref() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); - let pm_data_encrypted = create_encrypted_data(&key_store, updated_pmd).await; + let pm_data_encrypted = create_encrypted_data(&key_store, updated_pmd) + .await + .map(|details| details.into()); let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: pm_data_encrypted, @@ -2226,12 +2235,13 @@ pub async fn list_payment_methods( .then_some(billing_address.as_ref()) .flatten(); - let req = api_models::payments::PaymentsRequest::foreign_from(( + let req = api_models::payments::PaymentsRequest::foreign_try_from(( payment_attempt.as_ref(), + payment_intent.as_ref(), shipping_address.as_ref(), billing_address_for_calculating_required_fields, customer.as_ref(), - )); + ))?; let req_val = serde_json::to_value(req).ok(); logger::debug!(filtered_payment_methods=?response); @@ -4374,14 +4384,13 @@ pub async fn delete_payment_method( pub async fn create_encrypted_data<T>( key_store: &domain::MerchantKeyStore, data: Option<T>, -) -> Option<Encryption> +) -> Option<Encryptable<Secret<serde_json::Value>>> where T: Debug + serde::Serialize, { let key = key_store.key.get_inner().peek(); - let encrypted_data: Option<Encryption> = data - .as_ref() + data.as_ref() .map(Encode::encode_to_value) .transpose() .change_context(errors::StorageError::SerializationFailed) @@ -4399,9 +4408,6 @@ where logger::error!(err=?err); None }) - .map(|details| details.into()); - - encrypted_data } pub async fn list_countries_currencies_for_connector_payment_method( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a60d75100db..a16f5ca44fa 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -18,7 +18,7 @@ use error_stack::{report, ResultExt}; use futures::future::Either; use hyperswitch_domain_models::{ mandates::MandateData, - payments::{payment_attempt::PaymentAttempt, PaymentIntent}, + payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData, PaymentIntent}, router_data::KlarnaSdkResponse, }; use josekit::jwe; @@ -44,7 +44,11 @@ use crate::{ authentication, errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers::MandateGenericData, - payment_methods::{self, cards, vault}, + payment_methods::{ + self, + cards::{self, create_encrypted_data}, + vault, + }, payments, pm_auth::retrieve_payment_method_from_auth_service, }, @@ -1580,6 +1584,61 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( .get_required_value("customer") .change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?; + let temp_customer_data = if request_customer_details.name.is_some() + || request_customer_details.email.is_some() + || request_customer_details.phone.is_some() + || request_customer_details.phone_country_code.is_some() + { + Some(CustomerData { + name: request_customer_details.name.clone(), + email: request_customer_details.email.clone(), + phone: request_customer_details.phone.clone(), + phone_country_code: request_customer_details.phone_country_code.clone(), + }) + } else { + None + }; + + // Updation of Customer Details for the cases where both customer_id and specific customer + // details are provided in Payment Update Request + let raw_customer_details = payment_data + .payment_intent + .customer_details + .clone() + .map(|customer_details_encrypted| { + customer_details_encrypted + .into_inner() + .expose() + .parse_value::<CustomerData>("CustomerData") + }) + .transpose() + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to parse customer data from payment intent")? + .map(|parsed_customer_data| CustomerData { + name: request_customer_details + .name + .clone() + .or(parsed_customer_data.name.clone()), + email: request_customer_details + .email + .clone() + .or(parsed_customer_data.email.clone()), + phone: request_customer_details + .phone + .clone() + .or(parsed_customer_data.phone.clone()), + phone_country_code: request_customer_details + .phone_country_code + .clone() + .or(parsed_customer_data.phone_country_code.clone()), + }) + .or(temp_customer_data); + + payment_data.payment_intent.customer_details = raw_customer_details + .clone() + .async_and_then(|_| async { create_encrypted_data(key_store, raw_customer_details).await }) + .await; + let customer_id = request_customer_details .customer_id .or(payment_data.payment_intent.customer_id.clone()); @@ -3062,6 +3121,7 @@ mod tests { request_external_three_ds_authentication: None, charges: None, frm_metadata: None, + customer_details: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok()); @@ -3121,6 +3181,7 @@ mod tests { request_external_three_ds_authentication: None, charges: None, frm_metadata: None, + customer_details: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err()) @@ -3179,6 +3240,7 @@ mod tests { request_external_three_ds_authentication: None, charges: None, frm_metadata: None, + customer_details: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err()) diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index bfd63111e27..9c1e753776a 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1084,6 +1084,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen None }; + let customer_details = payment_data.payment_intent.customer_details.clone(); let business_sub_label = payment_data.payment_attempt.business_sub_label.clone(); let authentication_type = payment_data.payment_attempt.authentication_type; @@ -1255,6 +1256,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen session_expiry, request_external_three_ds_authentication: None, frm_metadata: m_frm_metadata, + customer_details, }, &m_key_store, storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 870fd78abe3..63ae07868a7 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -12,7 +12,8 @@ use diesel_models::{ephemeral_key, PaymentMethod}; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ mandates::{MandateData, MandateDetails}, - payments::payment_attempt::PaymentAttempt, + payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData}, + type_encryption::decrypt, }; use masking::{ExposeInterface, PeekInterface, Secret}; use router_derive::PaymentOperation; @@ -26,6 +27,7 @@ use crate::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers as m_helpers, payment_link, + payment_methods::cards::create_encrypted_data, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, @@ -245,8 +247,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa }; let payment_intent_new = Self::make_payment_intent( + state, &payment_id, merchant_account, + merchant_key_store, money, request, shipping_address @@ -560,7 +564,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentData<F>, - _customer: Option<domain::Customer>, + customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, @@ -628,16 +632,30 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let customer_id = payment_data.payment_intent.customer_id.clone(); + let raw_customer_details = customer + .map(|customer| CustomerData::try_from(customer.clone())) + .transpose()?; + + // Updation of Customer Details for the cases where both customer_id and specific customer + // details are provided in Payment Create Request + let customer_details = raw_customer_details + .clone() + .async_and_then(|_| async { + create_encrypted_data(key_store, raw_customer_details).await + }) + .await; + payment_data.payment_intent = state .store .update_payment_intent( payment_data.payment_intent, - storage::PaymentIntentUpdate::ReturnUrlUpdate { + storage::PaymentIntentUpdate::PaymentCreateUpdate { return_url: None, status, customer_id, shipping_address_id: None, billing_address_id: None, + customer_details, updated_by: storage_scheme.to_string(), }, key_store, @@ -815,7 +833,7 @@ impl PaymentCreate { additional_pm_data = payment_method_info .as_ref() .async_map(|pm_info| async { - domain::types::decrypt::<serde_json::Value, masking::WithType>( + decrypt::<serde_json::Value, masking::WithType>( pm_info.payment_method_data.clone(), key_store.key.get_inner().peek(), ) @@ -956,8 +974,10 @@ impl PaymentCreate { #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] async fn make_payment_intent( + _state: &SessionState, payment_id: &str, merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, money: (api::Amount, enums::Currency), request: &api::PaymentsRequest, shipping_address_id: Option<String>, @@ -1023,6 +1043,30 @@ impl PaymentCreate { .change_context(errors::ApiErrorResponse::InternalServerError)? .map(Secret::new); + // Derivation of directly supplied Customer data in our Payment Create Request + let raw_customer_details = if request.customer_id.is_none() + && (request.name.is_some() + || request.email.is_some() + || request.phone.is_some() + || request.phone_country_code.is_some()) + { + Some(CustomerData { + name: request.name.clone(), + phone: request.phone.clone(), + email: request.email.clone(), + phone_country_code: request.phone_country_code.clone(), + }) + } else { + None + }; + + // Encrypting our Customer Details to be stored in Payment Intent + let customer_details = if raw_customer_details.is_some() { + create_encrypted_data(key_store, raw_customer_details).await + } else { + None + }; + Ok(storage::PaymentIntent { payment_id: payment_id.to_string(), merchant_id: merchant_account.merchant_id.to_string(), @@ -1070,6 +1114,7 @@ impl PaymentCreate { .request_external_three_ds_authentication, charges, frm_metadata: request.frm_metadata.clone(), + customer_details, }) } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index a299b70e89b..8095660d4f2 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -4,8 +4,12 @@ use api_models::{ enums::FrmSuggestion, mandates::RecurringDetails, payments::RequestSurchargeDetails, }; use async_trait::async_trait; -use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; +use common_utils::{ + ext_traits::{AsyncExt, Encode, ValueExt}, + pii::Email, +}; use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::payments::payment_intent::CustomerData; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -661,7 +665,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let customer_id = customer.map(|c| c.customer_id); + let customer_id = customer.clone().map(|c| c.customer_id); let intent_status = { let current_intent_status = payment_data.payment_intent.status; @@ -681,6 +685,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_data.payment_intent.billing_address_id.clone(), ); + let customer_details = payment_data.payment_intent.customer_details.clone(); + let return_url = payment_data.payment_intent.return_url.clone(); let setup_future_usage = payment_data.payment_intent.setup_future_usage; let business_label = payment_data.payment_intent.business_label.clone(); @@ -726,6 +732,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .payment_intent .request_external_three_ds_authentication, frm_metadata, + customer_details, }, key_store, storage_scheme, @@ -740,6 +747,18 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen } } +impl TryFrom<domain::Customer> for CustomerData { + type Error = errors::ApiErrorResponse; + fn try_from(value: domain::Customer) -> Result<Self, Self::Error> { + Ok(Self { + name: value.name.map(|name| name.into_inner()), + email: value.email.map(Email::from), + phone: value.phone.map(|ph| ph.into_inner()), + phone_country_code: value.phone_country_code, + }) + } +} + impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate { #[instrument(skip_all)] fn validate_request<'a, 'b>( diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 161a9a43532..d6ceeee65e7 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -210,14 +210,17 @@ where }); let pm_data_encrypted = - payment_methods::cards::create_encrypted_data(key_store, pm_card_details).await; + payment_methods::cards::create_encrypted_data(key_store, pm_card_details) + .await + .map(|details| details.into()); let encrypted_payment_method_billing_address = payment_methods::cards::create_encrypted_data( key_store, payment_method_billing_address, ) - .await; + .await + .map(|details| details.into()); let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; @@ -509,7 +512,8 @@ where key_store, updated_pmd, ) - .await; + .await + .map(|details| details.into()); let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 0dbbbbf674a..9fcce65fbaf 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1,16 +1,17 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr}; use api_models::payments::{ - FrmMessage, GetAddressFromPaymentMethodData, PaymentChargeRequest, PaymentChargeResponse, - RequestSurchargeDetails, + CustomerDetailsResponse, FrmMessage, GetAddressFromPaymentMethodData, PaymentChargeRequest, + PaymentChargeResponse, RequestSurchargeDetails, }; #[cfg(feature = "payouts")] use api_models::payouts::PayoutAttemptResponse; use common_enums::RequestIncrementalAuthorization; -use common_utils::{consts::X_HS_LATENCY, fp_utils, types::MinorUnit}; +use common_utils::{consts::X_HS_LATENCY, fp_utils, pii::Email, types::MinorUnit}; use diesel_models::ephemeral_key; use error_stack::{report, ResultExt}; -use masking::{Maskable, PeekInterface, Secret}; +use hyperswitch_domain_models::payments::payment_intent::CustomerData; +use masking::{ExposeInterface, Maskable, PeekInterface, Secret}; use router_env::{instrument, metrics::add_attributes, tracing}; use super::{flows::Feature, types::AuthenticationData, PaymentData}; @@ -506,7 +507,47 @@ where )) } - let customer_details_response = customer.as_ref().map(ForeignInto::foreign_into); + // For the case when we don't have Customer data directly stored in Payment intent + let customer_table_response: Option<CustomerDetailsResponse> = + customer.as_ref().map(ForeignInto::foreign_into); + + // If we have customer data in Payment Intent, We are populating the Retrieve response from the + // same + let customer_details_response = + if let Some(customer_details_raw) = payment_intent.customer_details.clone() { + let customer_details_encrypted = + serde_json::from_value::<CustomerData>(customer_details_raw.into_inner().expose()); + if let Ok(customer_details_encrypted_data) = customer_details_encrypted { + Some(CustomerDetailsResponse { + id: customer_table_response.and_then(|customer_data| customer_data.id), + name: customer_details_encrypted_data + .name + .or(customer.as_ref().and_then(|customer| { + customer.name.as_ref().map(|name| name.clone().into_inner()) + })), + email: customer_details_encrypted_data.email.or(customer + .as_ref() + .and_then(|customer| customer.email.clone().map(Email::from))), + phone: customer_details_encrypted_data + .phone + .or(customer.as_ref().and_then(|customer| { + customer + .phone + .as_ref() + .map(|phone| phone.clone().into_inner()) + })), + phone_country_code: customer_details_encrypted_data.phone_country_code.or( + customer + .as_ref() + .and_then(|customer| customer.phone_country_code.clone()), + ), + }) + } else { + customer_table_response + } + } else { + customer_table_response + }; headers.extend( external_latency diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 0b54205bf67..6106ef29917 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -449,7 +449,9 @@ pub async fn save_payout_data_to_locker( ) }); ( - cards::create_encrypted_data(key_store, Some(pm_data)).await, + cards::create_encrypted_data(key_store, Some(pm_data)) + .await + .map(|details| details.into()), payment_method, ) } else { diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index e31a4dd75c7..e78c2153bb7 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -421,6 +421,7 @@ async fn store_bank_details_in_payment_methods( let encrypted_data = cards::create_encrypted_data(&key_store, Some(payment_method_data)) .await + .map(|details| details.into()) .ok_or(ApiErrorResponse::InternalServerError)?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: Some(encrypted_data), @@ -432,6 +433,7 @@ async fn store_bank_details_in_payment_methods( let encrypted_data = cards::create_encrypted_data(&key_store, Some(payment_method_data)) .await + .map(|details| details.into()) .ok_or(ApiErrorResponse::InternalServerError)?; let pm_id = generate_id(consts::ID_LENGTH, "pm"); let now = common_utils::date_time::now(); diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 57fc613af77..894f0ee95a8 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -14,6 +14,7 @@ use common_utils::{ }; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::payments::payment_intent::CustomerData; use masking::{ExposeInterface, PeekInterface}; use super::domain; @@ -1140,33 +1141,60 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { } impl - ForeignFrom<( + ForeignTryFrom<( Option<&storage::PaymentAttempt>, + Option<&storage::PaymentIntent>, Option<&domain::Address>, Option<&domain::Address>, Option<&domain::Customer>, )> for payments::PaymentsRequest { - fn foreign_from( + type Error = error_stack::Report<errors::ApiErrorResponse>; + fn foreign_try_from( value: ( Option<&storage::PaymentAttempt>, + Option<&storage::PaymentIntent>, Option<&domain::Address>, Option<&domain::Address>, Option<&domain::Customer>, ), - ) -> Self { - let (payment_attempt, shipping, billing, customer) = value; - Self { + ) -> Result<Self, Self::Error> { + let (payment_attempt, payment_intent, shipping, billing, customer) = value; + // Populating the dynamic fields directly, for the cases where we have customer details stored in + // Payment Intent + let customer_details_from_pi = payment_intent + .and_then(|payment_intent| payment_intent.customer_details.clone()) + .map(|customer_details| { + customer_details + .into_inner() + .peek() + .clone() + .parse_value::<CustomerData>("CustomerData") + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "customer_details", + }) + .attach_printable("Failed to parse customer_details") + }) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "customer_details", + })?; + Ok(Self { currency: payment_attempt.map(|pa| pa.currency.unwrap_or_default()), shipping: shipping.map(api_types::Address::from), billing: billing.map(api_types::Address::from), amount: payment_attempt.map(|pa| api_types::Amount::from(pa.amount)), email: customer - .and_then(|cust| cust.email.as_ref().map(|em| pii::Email::from(em.clone()))), - phone: customer.and_then(|cust| cust.phone.as_ref().map(|p| p.clone().into_inner())), - name: customer.and_then(|cust| cust.name.as_ref().map(|n| n.clone().into_inner())), + .and_then(|cust| cust.email.as_ref().map(|em| pii::Email::from(em.clone()))) + .or(customer_details_from_pi.clone().and_then(|cd| cd.email)), + phone: customer + .and_then(|cust| cust.phone.as_ref().map(|p| p.clone().into_inner())) + .or(customer_details_from_pi.clone().and_then(|cd| cd.phone)), + name: customer + .and_then(|cust| cust.name.as_ref().map(|n| n.clone().into_inner())) + .or(customer_details_from_pi.clone().and_then(|cd| cd.name)), ..Self::default() - } + }) } } @@ -1266,7 +1294,7 @@ impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse { impl ForeignFrom<&domain::Customer> for payments::CustomerDetailsResponse { fn foreign_from(customer: &domain::Customer) -> Self { Self { - id: customer.customer_id.clone(), + id: Some(customer.customer_id.clone()), name: customer .name .as_ref() diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index a2909e5f3c7..97c063eb3ae 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -225,6 +225,7 @@ pub async fn generate_sample_data( request_external_three_ds_authentication: None, charges: None, frm_metadata: Default::default(), + customer_details: None, }; let payment_attempt = PaymentAttemptBatchNew { attempt_id: attempt_id.clone(), diff --git a/migrations/2024-06-12-060604_add_customer_details_in_payment_intent/down.sql b/migrations/2024-06-12-060604_add_customer_details_in_payment_intent/down.sql new file mode 100644 index 00000000000..9b7bb65f082 --- /dev/null +++ b/migrations/2024-06-12-060604_add_customer_details_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 customer_details; diff --git a/migrations/2024-06-12-060604_add_customer_details_in_payment_intent/up.sql b/migrations/2024-06-12-060604_add_customer_details_in_payment_intent/up.sql new file mode 100644 index 00000000000..8a92056017c --- /dev/null +++ b/migrations/2024-06-12-060604_add_customer_details_in_payment_intent/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS customer_details BYTEA DEFAULT NULL;
2024-06-13T20:06:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This change will insure storage of customer_details in our payment_intent table. if customer_id alone is passed -> Derive customer_details from customer_table and put it in guest_customer_details, if customer_id is not present -> Put the details in guest_customer_details. if both are present -> we are ignoring the email, phone etc and deriving them from customer_table and adding to the guest_customer_details field. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables The Db Migration: ``` ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS customer_details BYTEA DEFAULT NULL; ``` <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### Testing Scenarios ![Screenshot 2024-06-27 at 6 07 09 PM](https://github.com/juspay/hyperswitch/assets/61520228/a5d4078b-e121-49bb-abb9-4a071764b266) ### Payment create request with no `cus_id` and fields name, email, phone, phone country code ``` Response should be populated like this ``` "customer_id": null, "customer": { "id": null, "name": "light", "email": "guest@example.com", "phone": "9xxxxxxxxx", "phone_country_code": "+91" }, ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "email": "guest@example.com", "name": "light", "phone": "9xxxxxxxxx", "phone_country_code": "+91", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` <img width="1728" alt="Screenshot 2024-06-14 at 1 34 46 AM" src="https://github.com/juspay/hyperswitch/assets/61520228/13981494-97a5-4442-b1f0-aa14bdf539cb"> ### Payment create request with some random `cus_id` ``` Response should be populated like this ``` "customer_id": "id_12343", "customer": { "id": null, "name": null, "email": null, "phone": null, "phone_country_code": null }, ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "id_12343", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` ### Payment create request with a created customer's `cus_id` ``` Response should be populated like this ``` "customer_id": "id_12343", "customer": { "id": null, "name": null, "email": null, "phone": null, "phone_country_code": null }, ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "id_12343", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` ### Payment create request with `cus_id` and all other data ``` Response should be populated like this ``` "customer_id": null, "customer": { "id": null, "name": "light", "email": "guest@example.com", "phone": "9xxxxxxxxx", "phone_country_code": "+91" }, ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "id_12343", "name": "light", "email": "guest@example.com", "phone": "9xxxxxxxxx", "phone_country_code": "+91", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` ### Payment create request with name and payment confirm with email and phone ``` Response should be populated like this after confirm request ``` "customer_id": null, "customer": { "id": null, "name": "light", "email": "guest@example.com", "phone": "9xxxxxxxxx", "phone_country_code": null }, ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "name": "light", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` ``` curl --location 'http://127.0.0.1:8080/payments/pay_7m0meCohmJxQJ4RzzlTm/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxxxxxxxxx' \ --data-raw '{ "email": "guest@example.com", "phone": "9xxxxxxxxx", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000003920000003", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } } }' ``` ### Payment create request with name and payment update with email and phone ``` Response should be populated like this after update request ``` "customer_id": null, "customer": { "id": null, "name": "light", "email": "payme@example.com", "phone": "9xxxxxxxxx", "phone_country_code": null }, ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "name": "light", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` ``` curl --location 'http://127.0.0.1:8080/payments/pay_7m0meCohmJxQJ4RzzlTm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Sz1d4HlpPQ71WmZksJ7NghSNmy64WGRkAFy0vhOmTA5QrDUVYNRb43ZSFySsz5KX' \ --data-raw '{ "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "2035", "card_holder_name": "John Doe", "card_cvc": "123" } }, "email": "payme@example.com", "phone": "9xxxxxxxxx" }' ``` ### Payment create request with id, name and payment update with email and phone ``` Response should be populated like this after update request ``` "customer_id": "id_12343", "customer": { "id": "id_12343", "name": "light", "email": "payme@example.com", "phone": "9xxxxxxxxx", "phone_country_code": null }, ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "id_12343", "name": "light", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` ``` curl --location 'http://127.0.0.1:8080/payments/pay_7m0meCohmJxQJ4RzzlTm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Sz1d4HlpPQ71WmZksJ7NghSNmy64WGRkAFy0vhOmTA5QrDUVYNRb43ZSFySsz5KX' \ --data-raw '{ "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "2035", "card_holder_name": "John Doe", "card_cvc": "123" } }, "email": "payme@example.com", "phone": "9xxxxxxxxx" }' ``` ### MCA of BOA, email in Payment create request and then List Payment Method with client secret ``` Response should be populated like this after update request ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "94122" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "payme@example.com" }, ........ ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:xxxxx' \ --data-raw ' { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "email": "payme@example.com", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` ``` curl --location 'http://127.0.0.1:8080/account/payment_methods?client_secret=pay_7m0meCohmJxQJ4RzzlTm_secret_ybvSTH07m5MGTGQDHA3R' \ --header 'Accept: application/json' \ --header 'api-key: xxxxxxxxx' \ --data '' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d4dba55fedc37ba9d1d54d28456ca17851ab9881
juspay/hyperswitch
juspay__hyperswitch-5002
Bug: chore: address Rust 1.79 clippy lints Address the clippy lints occurring due to new rust version 1.79 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index 9a0d4ec62c6..1ab79f07e43 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -317,6 +317,7 @@ impl std::fmt::Display for Order { // "count", // Order::Descending, // ) +#[allow(dead_code)] #[derive(Debug)] pub struct TopN { pub columns: String, diff --git a/crates/router/src/connector/globalpay/response.rs b/crates/router/src/connector/globalpay/response.rs index 7d5efadaff8..95f8c33728e 100644 --- a/crates/router/src/connector/globalpay/response.rs +++ b/crates/router/src/connector/globalpay/response.rs @@ -377,31 +377,11 @@ pub enum GlobalpayPaymentStatus { Reversed, } -#[derive(Debug, Deserialize)] -pub struct GlobalpayWebhoookResourceObject { - pub data: GlobalpayWebhookDataResource, -} - -#[derive(Debug, Deserialize)] -pub struct GlobalpayWebhookDataResource { - pub object: serde_json::Value, -} - #[derive(Debug, Deserialize)] pub struct GlobalpayWebhookObjectId { pub id: String, } -#[derive(Debug, Deserialize)] -pub struct GlobalpayWebhookDataId { - pub object: GlobalpayWebhookObjectDataId, -} - -#[derive(Debug, Deserialize)] -pub struct GlobalpayWebhookObjectDataId { - pub id: String, -} - #[derive(Debug, Deserialize)] pub struct GlobalpayWebhookObjectEventType { pub status: GlobalpayWebhookStatus, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index ff703dd84ef..9ec7e1bd38c 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -83,7 +83,6 @@ impl AdyenTest { use common_utils::pii::Email; Some(PaymentInfo { - country: Some(api_models::enums::CountryAlpha2::NL), currency: Some(enums::Currency::EUR), address: Some(PaymentAddress::new( None, diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs index 6554ddbefbf..045d356066d 100644 --- a/crates/router/tests/connectors/payme.rs +++ b/crates/router/tests/connectors/payme.rs @@ -68,7 +68,6 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { return_url: None, connector_customer: None, payment_method_token: None, - country: None, currency: None, #[cfg(feature = "payouts")] payout_method_data: None, diff --git a/crates/router/tests/connectors/square.rs b/crates/router/tests/connectors/square.rs index 2dcd93cc105..db7dd933e8c 100644 --- a/crates/router/tests/connectors/square.rs +++ b/crates/router/tests/connectors/square.rs @@ -48,7 +48,6 @@ fn get_default_payment_info(payment_method_token: Option<String>) -> Option<util #[cfg(feature = "payouts")] payout_method_data: None, currency: None, - country: None, }) } diff --git a/crates/router/tests/connectors/stax.rs b/crates/router/tests/connectors/stax.rs index 421ad9524c3..e1c139e9418 100644 --- a/crates/router/tests/connectors/stax.rs +++ b/crates/router/tests/connectors/stax.rs @@ -51,7 +51,6 @@ fn get_default_payment_info( #[cfg(feature = "payouts")] payout_method_data: None, currency: None, - country: None, }) } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 596b3ed6069..d98f0dae4ac 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -51,7 +51,6 @@ pub struct PaymentInfo { #[cfg(feature = "payouts")] pub payout_method_data: Option<types::api::PayoutMethodData>, pub currency: Option<enums::Currency>, - pub country: Option<enums::CountryAlpha2>, } impl PaymentInfo { diff --git a/crates/router/tests/connectors/wise.rs b/crates/router/tests/connectors/wise.rs index 161fd27f03d..47b799324ac 100644 --- a/crates/router/tests/connectors/wise.rs +++ b/crates/router/tests/connectors/wise.rs @@ -52,7 +52,6 @@ impl utils::Connector for WiseTest { impl WiseTest { fn get_payout_info() -> Option<PaymentInfo> { Some(PaymentInfo { - country: Some(api_models::enums::CountryAlpha2::NL), currency: Some(enums::Currency::GBP), address: Some(PaymentAddress::new( None,
2024-06-13T17:18:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR addresses the clippy lints occurring due to new rust version 1.79 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Basic sanity testing should suffice ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ad7886a6ff636f99e62601483c907f5c90954eb4
juspay/hyperswitch
juspay__hyperswitch-5014
Bug: Updating the API reference documentation We have had feedback related to the API doc being outdated, and lacking proper visibility of the latest spec of the API collection.
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index b11037c2a43..e1ebb547f05 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -857,9 +857,11 @@ pub struct ToggleAllKVResponse { #[schema(example = true)] pub kv_enabled: bool, } + +/// Merchant connector details used to make payments. #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MerchantConnectorDetailsWrap { - /// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info in this field. And do not send the string "null". + /// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info, like encoded_data in this field. And do not send the string "null". pub creds_identifier: String, /// Merchant connector details type type. Base64 Encode the credentials and send it in this type and send as a string. #[schema(value_type = Option<MerchantConnectorDetails>, example = r#"{ diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 514e44337c1..1f2896700e9 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -572,6 +572,7 @@ mod test { } } +/// Denotes the retry action #[derive( Debug, serde::Deserialize, diff --git a/crates/api_models/src/ephemeral_key.rs b/crates/api_models/src/ephemeral_key.rs index 42f5a087767..d7ee7bd2517 100644 --- a/crates/api_models/src/ephemeral_key.rs +++ b/crates/api_models/src/ephemeral_key.rs @@ -2,6 +2,7 @@ use common_utils::id_type; use serde; use utoipa::ToSchema; +/// ephemeral_key for the customer_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct EphemeralKeyCreateResponse { /// customer_id to which this ephemeral key belongs to diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 4adda0d9af4..f4089a16c22 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -114,6 +114,7 @@ pub struct MandateListConstraints { pub created_time_gte: Option<PrimitiveDateTime>, } +/// Details required for recurring payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RecurringDetails { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 2b06afc639f..08388f8db2d 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -179,6 +179,7 @@ mod client_secret_tests { } } +/// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. @@ -202,6 +203,7 @@ pub struct CustomerDetails { pub phone_country_code: Option<String>, } +/// Details of customer attached to this payment #[derive(Debug, Default, serde::Serialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The identifier for the customer. @@ -267,6 +269,7 @@ pub struct PaymentsRequest { /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825")] + #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<String>, #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ @@ -279,11 +282,9 @@ pub struct PaymentsRequest { #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, - /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, - /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, @@ -294,6 +295,7 @@ pub struct PaymentsRequest { /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable) @@ -342,16 +344,14 @@ pub struct PaymentsRequest { /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, - /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. + #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, - /// The payment method information provided for making a payment #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, - /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, @@ -361,6 +361,7 @@ pub struct PaymentsRequest { /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] + #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment @@ -391,7 +392,7 @@ pub struct PaymentsRequest { /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, - /// Passing this object during payments confirm . The customer_acceptance sub object is usually passed by the SDK or client + /// We will be Passing this "CustomerAcceptance" object during Payments-Confirm. The customer_acceptance sub object is usually passed by the SDK or client #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, @@ -418,7 +419,7 @@ pub struct PaymentsRequest { #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, - /// Payment Method Type + /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, @@ -434,7 +435,6 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, - /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, @@ -448,23 +448,24 @@ pub struct PaymentsRequest { /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] + #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, - /// additional data related to some connectors + /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, - /// additional data that might be required by hyperswitch + /// Additional data that might be required by hyperswitch based on the requested features by the merchants. + #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to get the payment link (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, - /// custom payment link config for the particular payment #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, @@ -473,7 +474,6 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub profile_id: Option<String>, - /// surcharge_details for this payment #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, @@ -490,7 +490,7 @@ pub struct PaymentsRequest { #[schema(example = 900)] pub session_expiry: Option<u32>, - /// additional data related to some frm connectors + /// additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, @@ -505,6 +505,7 @@ pub struct PaymentsRequest { pub charges: Option<PaymentChargeRequest>, } +/// Fee information to be charged on the payment being collected #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PaymentChargeRequest { @@ -530,6 +531,8 @@ impl PaymentsRequest { .map(|amount| MinorUnit::from(amount) + surcharge_amount) } } + +/// details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] @@ -905,6 +908,7 @@ impl Default for MandateType { } } +/// We will be Passing this "CustomerAcceptance" object during Payments-Confirm. The customer_acceptance sub object is usually passed by the SDK or client #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { @@ -1462,6 +1466,7 @@ mod payment_method_data_serde { } } +/// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { #[serde(flatten)] @@ -3037,7 +3042,7 @@ pub struct PaymentsCaptureRequest { /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. - #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] + #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -3290,7 +3295,18 @@ pub struct ReceiverDetails { amount_remaining: Option<i64>, } -#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] +#[derive( + Setter, + Clone, + Default, + Debug, + PartialEq, + serde::Serialize, + ToSchema, + router_derive::PolymorphicSchema, +)] +#[generate_schemas(PaymentsCreateResponseOpenApi)] + pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. @@ -3306,7 +3322,6 @@ pub struct PaymentsResponse { #[schema(max_length = 255, example = "merchant_1668273825")] pub merchant_id: Option<String>, - /// The status of the current payment that was made #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, @@ -3323,7 +3338,7 @@ pub struct PaymentsResponse { #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: Option<MinorUnit>, - /// The amount which is already captured from the payment + /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = i64, example = 6540)] pub amount_received: Option<MinorUnit>, @@ -3355,14 +3370,13 @@ pub struct PaymentsResponse { )] pub customer_id: Option<id_type::CustomerId>, - /// Details of customer attached to this payment pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, - /// List of refund that happened on this intent + /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, @@ -3380,7 +3394,7 @@ pub struct PaymentsResponse { #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, - /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data + /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, @@ -3454,7 +3468,7 @@ pub struct PaymentsResponse { #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, - /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS + /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, @@ -3481,16 +3495,18 @@ pub struct PaymentsResponse { pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector + #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector + #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, - /// Payment Method Type + /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, @@ -3537,10 +3553,11 @@ pub struct PaymentsResponse { #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated - /// reference to the payment at connector side + /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, + /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment pub profile_id: Option<String>, @@ -3557,7 +3574,7 @@ pub struct PaymentsResponse { /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment pub merchant_connector_id: Option<String>, - /// If true incremental authorization can be performed on this payment + /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment @@ -3572,19 +3589,20 @@ pub struct PaymentsResponse { /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, - /// Date Time expiry of the payment + /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, - /// Payment Fingerprint + /// Payment Fingerprint, to identify a particular card. + /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, - /// Payment Method Id + /// Identifier for Payment Method pub payment_method_id: Option<String>, /// Payment Method Status @@ -3604,6 +3622,7 @@ pub struct PaymentsResponse { pub frm_metadata: Option<pii::SecretSerdeValue>, } +/// Fee information to be charged on the payment being collected #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentChargeResponse { /// Identifier for charge created for the payment @@ -3621,6 +3640,7 @@ pub struct PaymentChargeResponse { pub transfer_account_id: String, } +/// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless @@ -4227,6 +4247,7 @@ pub struct ApplepaySessionRequest { pub initiative_context: String, } +/// additional data related to some connectors #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, @@ -4633,7 +4654,7 @@ pub struct PaymentsCancelRequest { /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. - #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] + #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -4665,6 +4686,7 @@ pub struct PaymentsExternalAuthenticationRequest { pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } +/// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment @@ -4697,6 +4719,7 @@ pub enum ThreeDsCompletionIndicator { NotAvailable, } +/// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] @@ -4705,6 +4728,7 @@ pub enum DeviceChannel { Browser, } +/// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device @@ -4723,7 +4747,7 @@ pub struct SdkInformation { #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { - /// Indicates the trans status + /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, @@ -4731,13 +4755,13 @@ pub struct PaymentsExternalAuthenticationResponse { pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, - /// Unique identifier assigned by the EMVCo + /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, - /// Contains the JWS object created by the ACS for the ARes message + /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, @@ -4768,6 +4792,7 @@ pub struct PaymentsStartRequest { pub attempt_id: String, } +/// additional data that might be required by hyperswitch #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios @@ -4959,6 +4984,7 @@ mod tests { #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { + /// It's a token used for client side verification. pub client_secret: Option<String>, } @@ -4970,16 +4996,24 @@ pub struct PaymentLinkResponse { #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { + /// Identifier for Payment Link pub payment_link_id: String, + /// Identifier for Merchant pub merchant_id: String, + /// Payment Link pub link_to_pay: String, + /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, + /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, + /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, + /// Description for Payment Link pub description: Option<String>, + /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, @@ -5090,6 +5124,7 @@ pub struct PaymentLinkListResponse { pub data: Vec<PaymentLinkResponse>, } +/// custom payment link config for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] @@ -5111,6 +5146,7 @@ pub struct OrderDetailsWithStringAmount { pub product_img_link: Option<String>, } +/// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 5ee0bae6d61..2d64a61450d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -19,6 +19,7 @@ pub mod diesel_exports { }; } +/// The status of the attempt #[derive( Clone, Copy, @@ -205,6 +206,7 @@ impl AttemptStatus { } } +/// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, @@ -232,6 +234,7 @@ pub enum AuthenticationType { NoThreeDs, } +/// The status of the capture #[derive( Clone, Copy, @@ -308,6 +311,7 @@ pub enum BlocklistDataKind { ExtendedCardBin, } +/// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, @@ -1164,6 +1168,7 @@ pub enum MerchantStorageScheme { RedisKv, } +/// The status of the current payment that was made #[derive( Clone, Copy, @@ -1197,6 +1202,7 @@ pub enum IntentStatus { PartiallyCapturedAndCapturable, } +/// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[derive( Clone, Copy, @@ -1251,6 +1257,7 @@ pub enum PaymentMethodIssuerCode { JpBacs, } +/// Payment Method Status #[derive( Clone, Copy, @@ -1603,6 +1610,7 @@ pub enum CardNetwork { Maestro, } +/// Stage of the dispute #[derive( Clone, Copy, @@ -1627,6 +1635,7 @@ pub enum DisputeStage { PreArbitration, } +/// Status of the dispute #[derive( Clone, Debug, @@ -2499,6 +2508,7 @@ pub enum RoleScope { Organization, } +/// Indicates the transaction status #[derive( Clone, Default, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index a259559c51d..3b37824be35 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -350,6 +350,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsUpdateRequest, api_models::payments::PaymentsConfirmRequest, api_models::payments::PaymentsResponse, + api_models::payments::PaymentsCreateResponseOpenApi, api_models::payments::PaymentsStartRequest, api_models::payments::PaymentRetrieveBody, api_models::payments::PaymentsRetrieveRequest, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index a93be8828a2..66e6ce42962 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -191,7 +191,7 @@ ), ), responses( - (status = 200, description = "Payment created", body = PaymentsResponse), + (status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi), (status = 400, description = "Missing Mandatory fields") ), tag = "Payments", @@ -268,7 +268,7 @@ pub fn payments_retrieve() {} ) ), responses( - (status = 200, description = "Payment updated", body = PaymentsResponse), + (status = 200, description = "Payment updated", body = PaymentsCreateResponseOpenApi), (status = 400, description = "Missing mandatory fields") ), tag = "Payments", @@ -326,7 +326,7 @@ pub fn payments_update() {} ) ), responses( - (status = 200, description = "Payment confirmed", body = PaymentsResponse), + (status = 200, description = "Payment confirmed", body = PaymentsCreateResponseOpenApi), (status = 400, description = "Missing mandatory fields") ), tag = "Payments",
2024-06-11T19:46:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description This is regarding the API Reference Doc changes using OpenAPI. This PR just the doc changes for Payments - Create (Including the Payments - Response) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Partial resolution of #5014 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d2626fa3fe4216504fd0df216eea8462c87cce07
juspay/hyperswitch
juspay__hyperswitch-5005
Bug: [REFACTOR] add basic counter metrics for IMC Introduce metrics for IMC - * hits (successful read), * misses (failed read), * manual invalidations (done by applications) Also add eviction listener on moka that can help identify strategy based evictions.
diff --git a/crates/analytics/src/api_event/core.rs b/crates/analytics/src/api_event/core.rs index 7225a6322d4..c7d6d9ac339 100644 --- a/crates/analytics/src/api_event/core.rs +++ b/crates/analytics/src/api_event/core.rs @@ -12,6 +12,7 @@ use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use router_env::{ instrument, logger, + metrics::add_attributes, tracing::{self, Instrument}, }; @@ -135,10 +136,10 @@ pub async fn get_api_event_metrics( .change_context(AnalyticsError::UnknownError)? { let data = data?; - let attributes = &[ - metrics::request::add_attributes("metric_type", metric.to_string()), - metrics::request::add_attributes("source", pool.to_string()), - ]; + let attributes = &add_attributes([ + ("metric_type", metric.to_string()), + ("source", pool.to_string()), + ]); let value = u64::try_from(data.len()); if let Ok(val) = value { diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs index dfba5fea112..d2279180255 100644 --- a/crates/analytics/src/disputes/core.rs +++ b/crates/analytics/src/disputes/core.rs @@ -11,6 +11,7 @@ use api_models::analytics::{ use error_stack::ResultExt; use router_env::{ logger, + metrics::add_attributes, tracing::{self, Instrument}, }; @@ -70,10 +71,10 @@ pub async fn get_metrics( .change_context(AnalyticsError::UnknownError)? { let data = data?; - let attributes = &[ - metrics::request::add_attributes("metric_type", metric.to_string()), - metrics::request::add_attributes("source", pool.to_string()), - ]; + let attributes = &add_attributes([ + ("metric_type", metric.to_string()), + ("source", pool.to_string()), + ]); let value = u64::try_from(data.len()); if let Ok(val) = value { diff --git a/crates/analytics/src/metrics/request.rs b/crates/analytics/src/metrics/request.rs index 3d1a78808f3..39375d391a3 100644 --- a/crates/analytics/src/metrics/request.rs +++ b/crates/analytics/src/metrics/request.rs @@ -1,9 +1,6 @@ -pub fn add_attributes<T: Into<router_env::opentelemetry::Value>>( - key: &'static str, - value: T, -) -> router_env::opentelemetry::KeyValue { - router_env::opentelemetry::KeyValue::new(key, value) -} +use std::time; + +use router_env::metrics::add_attributes; #[inline] pub async fn record_operation_time<F, R, T>( @@ -17,10 +14,10 @@ where T: ToString, { let (result, time) = time_future(future).await; - let attributes = &[ - add_attributes("metric_name", metric_name.to_string()), - add_attributes("source", source.to_string()), - ]; + let attributes = &add_attributes([ + ("metric_name", metric_name.to_string()), + ("source", source.to_string()), + ]); let value = time.as_secs_f64(); metric.record(&super::CONTEXT, value, attributes); @@ -28,8 +25,6 @@ where result } -use std::time; - #[inline] pub async fn time_future<F, R>(future: F) -> (R, time::Duration) where diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index a3f24b65a17..2508866626a 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -13,6 +13,7 @@ use common_utils::errors::CustomResult; use error_stack::ResultExt; use router_env::{ instrument, logger, + metrics::add_attributes, tracing::{self, Instrument}, }; @@ -120,10 +121,10 @@ pub async fn get_metrics( match task_type { TaskType::MetricTask(metric, data) => { let data = data?; - let attributes = &[ - metrics::request::add_attributes("metric_type", metric.to_string()), - metrics::request::add_attributes("source", pool.to_string()), - ]; + let attributes = &add_attributes([ + ("metric_type", metric.to_string()), + ("source", pool.to_string()), + ]); let value = u64::try_from(data.len()); if let Ok(val) = value { @@ -172,10 +173,10 @@ pub async fn get_metrics( } TaskType::DistributionTask(distribution, data) => { let data = data?; - let attributes = &[ - metrics::request::add_attributes("distribution_type", distribution.to_string()), - metrics::request::add_attributes("source", pool.to_string()), - ]; + let attributes = &add_attributes([ + ("distribution_type", distribution.to_string()), + ("source", pool.to_string()), + ]); let value = u64::try_from(data.len()); if let Ok(val) = value { diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs index b53d482e620..57480c7cec7 100644 --- a/crates/analytics/src/refunds/core.rs +++ b/crates/analytics/src/refunds/core.rs @@ -11,6 +11,7 @@ use api_models::analytics::{ use error_stack::ResultExt; use router_env::{ logger, + metrics::add_attributes, tracing::{self, Instrument}, }; @@ -69,10 +70,10 @@ pub async fn get_metrics( .change_context(AnalyticsError::UnknownError)? { let data = data?; - let attributes = &[ - metrics::request::add_attributes("metric_type", metric.to_string()), - metrics::request::add_attributes("source", pool.to_string()), - ]; + let attributes = &add_attributes([ + ("metric_type", metric.to_string()), + ("source", pool.to_string()), + ]); let value = u64::try_from(data.len()); if let Ok(val) = value { diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs index 63cbc6dabf8..ac397cfa075 100644 --- a/crates/hyperswitch_interfaces/src/api.rs +++ b/crates/hyperswitch_interfaces/src/api.rs @@ -6,6 +6,7 @@ use common_utils::{ }; use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData}; use masking::Maskable; +use router_env::metrics::add_attributes; use serde_json::json; use crate::{ @@ -87,7 +88,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re metrics::UNIMPLEMENTED_FLOW.add( &metrics::CONTEXT, 1, - &[metrics::add_attributes("connector", req.connector.clone())], + &add_attributes([("connector", req.connector.clone())]), ); Ok(None) } diff --git a/crates/hyperswitch_interfaces/src/metrics.rs b/crates/hyperswitch_interfaces/src/metrics.rs index a03215a175d..fc374eba8e2 100644 --- a/crates/hyperswitch_interfaces/src/metrics.rs +++ b/crates/hyperswitch_interfaces/src/metrics.rs @@ -1,16 +1,8 @@ //! Metrics interface -use router_env::{counter_metric, global_meter, metrics_context, opentelemetry}; +use router_env::{counter_metric, global_meter, metrics_context}; metrics_context!(CONTEXT); global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER); - -/// fn add attributes -pub fn add_attributes<T: Into<opentelemetry::Value>>( - key: &'static str, - value: T, -) -> opentelemetry::KeyValue { - opentelemetry::KeyValue::new(key, value) -} diff --git a/crates/router/src/connector/boku.rs b/crates/router/src/connector/boku.rs index 7c456d2ec1c..d565cc6567e 100644 --- a/crates/router/src/connector/boku.rs +++ b/crates/router/src/connector/boku.rs @@ -6,6 +6,7 @@ use diesel_models::enums; use error_stack::{report, Report, ResultExt}; use masking::{ExposeInterface, PeekInterface, Secret, WithType}; use ring::hmac; +use router_env::metrics::add_attributes; use roxmltree; use time::OffsetDateTime; use transformers as boku; @@ -665,7 +666,7 @@ fn get_xml_deserialized( metrics::RESPONSE_DESERIALIZATION_FAILURE.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes("connector", "boku")], + &add_attributes([("connector", "boku")]), ); let response_data = String::from_utf8(res.response.to_vec()) diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index f7e142a9af9..750e2e6e3cc 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -155,7 +155,7 @@ impl ConnectorCommon for Braintree { Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_msg); - utils::handle_json_response_deserialization_failure(res, "braintree".to_owned()) + utils::handle_json_response_deserialization_failure(res, "braintree") } } } diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 1f8de468846..7bd3fa08dda 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -229,10 +229,7 @@ impl ConnectorCommon for Cybersource { Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); router_env::logger::error!(deserialization_error =? error_msg); - crate::utils::handle_json_response_deserialization_failure( - res, - "cybersource".to_owned(), - ) + crate::utils::handle_json_response_deserialization_failure(res, "cybersource") } } } diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index 23e15b2cfdc..909f7a435c1 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -155,7 +155,7 @@ impl ConnectorCommon for Noon { Err(error_message) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_message); - utils::handle_json_response_deserialization_failure(res, "noon".to_owned()) + utils::handle_json_response_deserialization_failure(res, "noon") } } } diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs index 397715d102d..88b2ec67595 100644 --- a/crates/router/src/connector/payme.rs +++ b/crates/router/src/connector/payme.rs @@ -111,7 +111,7 @@ impl ConnectorCommon for Payme { Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); router_env::logger::error!(deserialization_error =? error_msg); - handle_json_response_deserialization_failure(res, "payme".to_owned()) + handle_json_response_deserialization_failure(res, "payme") } } } diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index 5d4579fffa7..f4bd0997627 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -114,7 +114,7 @@ impl ConnectorCommon for Rapyd { Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_msg); - utils::handle_json_response_deserialization_failure(res, "rapyd".to_owned()) + utils::handle_json_response_deserialization_failure(res, "rapyd") } } } diff --git a/crates/router/src/connector/threedsecureio.rs b/crates/router/src/connector/threedsecureio.rs index 75a746648f1..a051cf471f1 100644 --- a/crates/router/src/connector/threedsecureio.rs +++ b/crates/router/src/connector/threedsecureio.rs @@ -126,10 +126,7 @@ impl ConnectorCommon for Threedsecureio { } Err(err) => { router_env::logger::error!(deserialization_error =? err); - utils::handle_json_response_deserialization_failure( - res, - "threedsecureio".to_owned(), - ) + utils::handle_json_response_deserialization_failure(res, "threedsecureio") } } } diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs index 1f9e77de9cd..e2904221e59 100644 --- a/crates/router/src/connector/trustpay.rs +++ b/crates/router/src/connector/trustpay.rs @@ -153,7 +153,7 @@ impl ConnectorCommon for Trustpay { Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_msg); - utils::handle_json_response_deserialization_failure(res, "trustpay".to_owned()) + utils::handle_json_response_deserialization_failure(res, "trustpay") } } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 71e91373454..b9ac5a02b7e 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -15,6 +15,7 @@ use error_stack::{report, FutureExt, ResultExt}; use futures::future::try_join_all; use masking::{PeekInterface, Secret}; use pm_auth::connector::plaid::transformers::PlaidAuthType; +use router_env::metrics::add_attributes; use uuid::Uuid; use crate::{ @@ -1009,10 +1010,10 @@ pub async fn create_payment_connector( metrics::MCA_CREATE.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes("connector", req.connector_name.to_string()), - metrics::request::add_attributes("merchant", merchant_id.to_string()), - ], + &add_attributes([ + ("connector", req.connector_name.to_string()), + ("merchant", merchant_id.to_string()), + ]), ); let mca_response = mca.try_into()?; diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index ef81e3c190d..5d41b9c1854 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -3,7 +3,7 @@ use common_utils::date_time; use diesel_models::{api_keys::ApiKey, enums as storage_enums}; use error_stack::{report, ResultExt}; use masking::{PeekInterface, StrongSecret}; -use router_env::{instrument, tracing}; +use router_env::{instrument, metrics::add_attributes, tracing}; use crate::{ configs::settings, @@ -151,7 +151,7 @@ pub async fn create_api_key( metrics::API_KEY_CREATED.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes("merchant", merchant_id)], + &add_attributes([("merchant", merchant_id)]), ); // Add process to process_tracker for email reminder, only if expiry is set to future date @@ -236,7 +236,7 @@ pub async fn add_api_key_expiry_task( metrics::TASKS_ADDED_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes("flow", "ApiKeyExpiry")], + &add_attributes([("flow", "ApiKeyExpiry")]), ); Ok(()) diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index f484467f354..9fa4b478217 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -5,7 +5,7 @@ use common_utils::{ext_traits::Encode, id_type}; use diesel_models::{enums as storage_enums, Mandate}; use error_stack::{report, ResultExt}; use futures::future; -use router_env::{instrument, logger, tracing}; +use router_env::{instrument, logger, metrics::add_attributes, tracing}; use super::payments::helpers as payment_helper; use crate::{ @@ -404,10 +404,7 @@ where metrics::SUBSEQUENT_MANDATE_PAYMENT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - mandate.connector, - )], + &add_attributes([("connector", mandate.connector)]), ); Ok(Some(mandate_id.clone())) } @@ -463,7 +460,7 @@ where metrics::MANDATE_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes("connector", connector)], + &add_attributes([("connector", connector)]), ); Ok(Some(res_mandate_id)) } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 66940fa9508..8df78d28187 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -36,7 +36,7 @@ use euclid::{ use hyperswitch_constraint_graph as cgraph; use kgraph_utils::transformers::IntoDirValue; use masking::Secret; -use router_env::{instrument, tracing}; +use router_env::{instrument, metrics::add_attributes, tracing}; use strum::IntoEnumIterator; use super::surcharge_decision_configs::{ @@ -3958,7 +3958,7 @@ impl TempLockerCardSupport { metrics::TASKS_ADDED_COUNT.add( &metrics::CONTEXT, 1, - &[request::add_attributes("flow", "DeleteTokenizeData")], + &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 f37385b80c6..4e17ec6abd3 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -7,7 +7,7 @@ use common_utils::{ }; use error_stack::{report, ResultExt}; use masking::PeekInterface; -use router_env::{instrument, tracing}; +use router_env::{instrument, metrics::add_attributes, tracing}; use scheduler::{types::process_data, utils as process_tracker_utils}; #[cfg(feature = "payouts")] @@ -1232,10 +1232,7 @@ pub async fn retry_delete_tokenize( metrics::TASKS_RESET_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "flow", - "DeleteTokenizeData", - )], + &add_attributes([("flow", "DeleteTokenizeData")]), ); retry_schedule } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 50eedcfb568..9cf46477b28 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -42,7 +42,7 @@ pub use hyperswitch_domain_models::{ }; use masking::{ExposeInterface, Secret}; use redis_interface::errors::RedisError; -use router_env::{instrument, tracing}; +use router_env::{instrument, metrics::add_attributes, tracing}; #[cfg(feature = "olap")] use router_types::transformers::ForeignFrom; use scheduler::utils as pt_utils; @@ -857,16 +857,13 @@ pub trait PaymentRedirectFlow: Sync { metrics::REDIRECTION_TRIGGERED.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( + &add_attributes([ + ( "connector", req.connector.to_owned().unwrap_or("null".to_string()), ), - metrics::request::add_attributes( - "merchant_id", - merchant_account.merchant_id.to_owned(), - ), - ], + ("merchant_id", merchant_account.merchant_id.to_owned()), + ]), ); let connector = req.connector.clone().get_required_value("connector")?; diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index 4241db6742d..a53a3d405a9 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -2,6 +2,7 @@ use std::fmt::Debug; use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; +use router_env::metrics::add_attributes; use crate::{ consts, @@ -94,10 +95,7 @@ pub async fn add_access_token< metrics::ACCESS_TOKEN_CACHE_HIT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - )], + &add_attributes([("connector", connector.connector_name.to_string())]), ); Ok(Some(access_token)) } @@ -105,10 +103,7 @@ pub async fn add_access_token< metrics::ACCESS_TOKEN_CACHE_MISS.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - )], + &add_attributes([("connector", connector.connector_name.to_string())]), ); let cloned_router_data = router_data.clone(); @@ -247,10 +242,7 @@ pub async fn refresh_connector_auth( metrics::ACCESS_TOKEN_CREATION.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - )], + &add_attributes([("connector", connector.connector_name.to_string())]), ); Ok(access_token_router_data) } diff --git a/crates/router/src/core/payments/customers.rs b/crates/router/src/core/payments/customers.rs index 448e5fedb8b..67fdd7746af 100644 --- a/crates/router/src/core/payments/customers.rs +++ b/crates/router/src/core/payments/customers.rs @@ -1,4 +1,4 @@ -use router_env::{instrument, tracing}; +use router_env::{instrument, metrics::add_attributes, tracing}; use crate::{ core::{ @@ -54,10 +54,7 @@ pub async fn create_connector_customer<F: Clone, T: Clone>( metrics::CONNECTOR_CUSTOMER_CREATE.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - )], + &add_attributes([("connector", connector.connector_name.to_string())]), ); let connector_customer_id = match resp.response { diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 7497ca6a9e5..433274587a8 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -1,4 +1,5 @@ use async_trait::async_trait; +use router_env::metrics::add_attributes; // use router_env::tracing::Instrument; use super::{ConstructFlowSpecificData, Feature}; @@ -209,13 +210,10 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu metrics::EXECUTE_PRETASK_COUNT.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - ), - metrics::request::add_attributes("flow", format!("{:?}", api::Authorize)), - ], + &add_attributes([ + ("connector", connector.connector_name.to_string()), + ("flow", format!("{:?}", api::Authorize)), + ]), ); logger::debug!(completed_pre_tasks=?true); @@ -333,13 +331,10 @@ pub async fn authorize_preprocessing_steps<F: Clone>( metrics::PREPROCESSING_STEPS_COUNT.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes("connector", connector.connector_name.to_string()), - metrics::request::add_attributes( - "payment_method", - router_data.payment_method.to_string(), - ), - metrics::request::add_attributes( + &add_attributes([ + ("connector", connector.connector_name.to_string()), + ("payment_method", router_data.payment_method.to_string()), + ( "payment_method_type", router_data .request @@ -348,7 +343,7 @@ pub async fn authorize_preprocessing_steps<F: Clone>( .map(|inner| inner.to_string()) .unwrap_or("null".to_string()), ), - ], + ]), ); let mut authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>( resp.clone(), diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index d7e8cc3d9b5..2a6774a91e2 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -1,4 +1,5 @@ use async_trait::async_trait; +use router_env::metrics::add_attributes; use super::{ConstructFlowSpecificData, Feature}; use crate::{ @@ -55,10 +56,7 @@ impl Feature<api::Void, types::PaymentsCancelData> metrics::PAYMENT_CANCEL_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - )], + &add_attributes([("connector", connector.connector_name.to_string())]), ); let connector_integration: services::BoxedConnectorIntegration< 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 5d0cb9f9f38..bb2c959f290 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -1,4 +1,5 @@ use async_trait::async_trait; +use router_env::metrics::add_attributes; use super::{ConstructFlowSpecificData, Feature}; use crate::{ @@ -191,13 +192,10 @@ pub async fn complete_authorize_preprocessing_steps<F: Clone>( metrics::PREPROCESSING_STEPS_COUNT.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes("connector", connector.connector_name.to_string()), - metrics::request::add_attributes( - "payment_method", - router_data.payment_method.to_string(), - ), - ], + &add_attributes([ + ("connector", connector.connector_name.to_string()), + ("payment_method", router_data.payment_method.to_string()), + ]), ); let mut router_data_request = router_data.request.to_owned(); diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 14a3b9327dc..e279e6f7c34 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -3,6 +3,7 @@ use async_trait::async_trait; use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::{Report, ResultExt}; use masking::ExposeInterface; +use router_env::metrics::add_attributes; use super::{ConstructFlowSpecificData, Feature}; use crate::{ @@ -64,10 +65,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio metrics::SESSION_TOKEN_CREATED.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - )], + &add_attributes([("connector", connector.connector_name.to_string())]), ); self.decide_flow( state, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 7eada733aed..49cc20528a1 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -26,7 +26,7 @@ use openssl::{ pkey::PKey, symm::{decrypt_aead, Cipher}, }; -use router_env::{instrument, logger, tracing}; +use router_env::{instrument, logger, metrics::add_attributes, tracing}; use uuid::Uuid; use x509_parser::parse_x509_certificate; @@ -1219,10 +1219,7 @@ where metrics::TASKS_ADDED_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "flow", - format!("{:#?}", operation), - )], + &add_attributes([("flow", format!("{:#?}", operation))]), ); super::add_process_sync_task(&*state.store, payment_attempt, stime) .await @@ -1233,10 +1230,7 @@ where metrics::TASKS_RESET_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "flow", - format!("{:#?}", operation), - )], + &add_attributes([("flow", format!("{:#?}", operation))]), ); super::reset_process_sync_task(&*state.store, payment_attempt, stime) .await @@ -3406,10 +3400,7 @@ pub fn get_attempt_type( metrics::MANUAL_RETRY_REQUEST_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "merchant_id", - payment_attempt.merchant_id.clone(), - )], + &add_attributes([("merchant_id", payment_attempt.merchant_id.clone())]), ); match payment_attempt.status { enums::AttemptStatus::Started @@ -3433,10 +3424,7 @@ pub fn get_attempt_type( metrics::MANUAL_RETRY_VALIDATION_FAILED.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "merchant_id", - payment_attempt.merchant_id.clone(), - )], + &add_attributes([("merchant_id", payment_attempt.merchant_id.clone())]), ); Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment Attempt unexpected state") @@ -3448,10 +3436,7 @@ pub fn get_attempt_type( metrics::MANUAL_RETRY_VALIDATION_FAILED.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "merchant_id", - payment_attempt.merchant_id.clone(), - )], + &add_attributes([("merchant_id", payment_attempt.merchant_id.clone())]), ); Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: @@ -3466,10 +3451,7 @@ pub fn get_attempt_type( metrics::MANUAL_RETRY_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "merchant_id", - payment_attempt.merchant_id.clone(), - )], + &add_attributes([("merchant_id", payment_attempt.merchant_id.clone())]), ); Ok(AttemptType::New) } diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b014f42a5ce..41a45c29d24 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -8,7 +8,7 @@ use common_utils::{ }; use error_stack::{report, ResultExt}; use masking::ExposeInterface; -use router_env::{instrument, tracing}; +use router_env::{instrument, metrics::add_attributes, tracing}; use super::helpers; use crate::{ @@ -762,16 +762,10 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( metrics::CONNECTOR_PAYMENT_METHOD_TOKENIZATION.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - ), - metrics::request::add_attributes( - "payment_method", - router_data.payment_method.to_string(), - ), - ], + &add_attributes([ + ("connector", connector.connector_name.to_string()), + ("payment_method", router_data.payment_method.to_string()), + ]), ); let pm_token = match resp.response { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 604bc5cda99..6b54427d87a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -11,7 +11,7 @@ use common_utils::{consts::X_HS_LATENCY, fp_utils, types::MinorUnit}; use diesel_models::ephemeral_key; use error_stack::{report, ResultExt}; use masking::{Maskable, PeekInterface, Secret}; -use router_env::{instrument, tracing}; +use router_env::{instrument, metrics::add_attributes, tracing}; use super::{flows::Feature, types::AuthenticationData, PaymentData}; use crate::{ @@ -844,12 +844,12 @@ where metrics::PAYMENT_OPS_COUNT.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes("operation", format!("{:?}", operation)), - metrics::request::add_attributes("merchant", merchant_id), - metrics::request::add_attributes("payment_method_type", payment_method_type), - metrics::request::add_attributes("payment_method", payment_method), - ], + &add_attributes([ + ("operation", format!("{:?}", operation)), + ("merchant", merchant_id), + ("payment_method_type", payment_method_type), + ("payment_method", payment_method), + ]), ); Ok(output) diff --git a/crates/router/src/core/payouts/access_token.rs b/crates/router/src/core/payouts/access_token.rs index 5e40720f4ef..2f1892af821 100644 --- a/crates/router/src/core/payouts/access_token.rs +++ b/crates/router/src/core/payouts/access_token.rs @@ -1,5 +1,6 @@ use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; +use router_env::metrics::add_attributes; use crate::{ consts, @@ -185,10 +186,7 @@ pub async fn refresh_connector_auth( metrics::ACCESS_TOKEN_CREATION.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - )], + &add_attributes([("connector", connector.connector_name.to_string())]), ); Ok(access_token_router_data) } diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 164fd1ec784..78b4762777f 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -12,7 +12,7 @@ use common_utils::{ use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; use masking::PeekInterface; -use router_env::{instrument, tracing}; +use router_env::{instrument, metrics::add_attributes, tracing}; use scheduler::{consumer::types::process_data, utils as process_tracker_utils}; #[cfg(feature = "olap")] use strum::IntoEnumIterator; @@ -154,10 +154,7 @@ pub async fn trigger_refund_to_gateway( metrics::REFUND_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - routed_through.clone(), - )], + &add_attributes([("connector", routed_through.clone())]), ); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( @@ -280,10 +277,7 @@ pub async fn trigger_refund_to_gateway( metrics::SUCCESSFUL_REFUND.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - connector.connector_name.to_string(), - )], + &add_attributes([("connector", connector.connector_name.to_string())]), ) } storage::RefundUpdate::Update { @@ -1246,11 +1240,7 @@ pub async fn add_refund_sync_task( refund.refund_id ) })?; - metrics::TASKS_ADDED_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes("flow", "Refund")], - ); + metrics::TASKS_ADDED_COUNT.add(&metrics::CONTEXT, 1, &add_attributes([("flow", "Refund")])); Ok(response) } diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 2f1a37981ec..503a67855d9 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -10,7 +10,7 @@ use api_models::{ use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; -use router_env::{instrument, tracing, tracing_actix_web::RequestId}; +use router_env::{instrument, metrics::add_attributes, tracing, tracing_actix_web::RequestId}; use super::{types, utils, MERCHANT_ID}; use crate::{ @@ -25,9 +25,7 @@ use crate::{ logger, routes::{ app::{ReqState, SessionStateInfo}, - lock_utils, - metrics::request::add_attributes, - SessionState, + lock_utils, SessionState, }, services::{self, authentication as auth}, types::{ @@ -567,10 +565,7 @@ async fn payments_incoming_webhook_flow( metrics::WEBHOOK_PAYMENT_NOT_FOUND.add( &metrics::CONTEXT, 1, - &[add_attributes( - "merchant_id", - merchant_account.merchant_id.clone(), - )], + &add_attributes([("merchant_id", merchant_account.merchant_id.clone())]), ); return Ok(WebhookResponseTracker::NoEffect); } diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index 07fe78f51ce..410d6c3d851 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -8,6 +8,7 @@ use error_stack::{report, ResultExt}; use masking::{ExposeInterface, Mask, PeekInterface, Secret}; use router_env::{ instrument, + metrics::add_attributes, tracing::{self, Instrument}, }; @@ -22,7 +23,7 @@ use crate::{ db::StorageInterface, events::outgoing_webhook_logs::{OutgoingWebhookEvent, OutgoingWebhookEventMetric}, logger, - routes::{app::SessionStateInfo, metrics::request::add_attributes, SessionState}, + routes::{app::SessionStateInfo, SessionState}, services, types::{ api, @@ -501,7 +502,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker( crate::routes::metrics::TASKS_ADDED_COUNT.add( &metrics::CONTEXT, 1, - &[add_attributes("flow", "OutgoingWebhookRetry")], + &add_attributes([("flow", "OutgoingWebhookRetry")]), ); Ok(process_tracker) } @@ -509,7 +510,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker( crate::routes::metrics::TASK_ADDITION_FAILURES_COUNT.add( &metrics::CONTEXT, 1, - &[add_attributes("flow", "OutgoingWebhookRetry")], + &add_attributes([("flow", "OutgoingWebhookRetry")]), ); Err(error) } diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index eef85410981..fffb5e20c9d 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -2,7 +2,7 @@ pub mod bg_metrics_collector; pub mod request; pub mod utils; -use router_env::{counter_metric, gauge_metric, global_meter, histogram_metric, metrics_context}; +use router_env::{counter_metric, global_meter, histogram_metric, metrics_context}; metrics_context!(CONTEXT); global_meter!(GLOBAL_METER, "ROUTER_API"); @@ -135,6 +135,3 @@ counter_metric!(ACCESS_TOKEN_CACHE_HIT, GLOBAL_METER); // A counter to indicate the access token cache miss counter_metric!(ACCESS_TOKEN_CACHE_MISS, GLOBAL_METER); - -// Metrics for In-memory cache -gauge_metric!(CACHE_ENTRY_COUNT, GLOBAL_METER); diff --git a/crates/router/src/routes/metrics/bg_metrics_collector.rs b/crates/router/src/routes/metrics/bg_metrics_collector.rs index 65cb7a13e5e..52d7777f5aa 100644 --- a/crates/router/src/routes/metrics/bg_metrics_collector.rs +++ b/crates/router/src/routes/metrics/bg_metrics_collector.rs @@ -2,40 +2,25 @@ use storage_impl::redis::cache; const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15; -macro_rules! gauge_metrics_for_imc { - ($($cache:ident),*) => { - $( - { - cache::$cache.run_pending_tasks().await; - - super::CACHE_ENTRY_COUNT.observe( - &super::CONTEXT, - cache::$cache.get_entry_count(), - &[super::request::add_attributes( - "cache_type", - stringify!($cache), - )], - ); - } - )* - }; -} - pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: &Option<u16>) { let metrics_collection_interval = metrics_collection_interval_in_secs .unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS); + let cache_instances = [ + &cache::CONFIG_CACHE, + &cache::ACCOUNTS_CACHE, + &cache::ROUTING_CACHE, + &cache::CGRAPH_CACHE, + &cache::PM_FILTERS_CGRAPH_CACHE, + &cache::DECISION_MANAGER_CACHE, + &cache::SURCHARGE_CACHE, + ]; + tokio::spawn(async move { loop { - gauge_metrics_for_imc!( - CONFIG_CACHE, - ACCOUNTS_CACHE, - ROUTING_CACHE, - CGRAPH_CACHE, - PM_FILTERS_CGRAPH_CACHE, - DECISION_MANAGER_CACHE, - SURCHARGE_CACHE - ); + for instance in cache_instances { + instance.record_entry_count_metric().await + } tokio::time::sleep(std::time::Duration::from_secs( metrics_collection_interval.into(), diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs index ef53ad83f2c..905f089a0c6 100644 --- a/crates/router/src/routes/metrics/request.rs +++ b/crates/router/src/routes/metrics/request.rs @@ -1,4 +1,4 @@ -use router_env::opentelemetry; +use router_env::{metrics::add_attributes, opentelemetry}; use super::utils as metric_utils; use crate::services::ApplicationResponse; @@ -11,12 +11,16 @@ where F: futures::Future<Output = R>, { let key = "request_type"; - super::REQUESTS_RECEIVED.add(&super::CONTEXT, 1, &[add_attributes(key, flow.to_string())]); + super::REQUESTS_RECEIVED.add( + &super::CONTEXT, + 1, + &add_attributes([(key, flow.to_string())]), + ); let (result, time) = metric_utils::time_future(future).await; super::REQUEST_TIME.record( &super::CONTEXT, time.as_secs_f64(), - &[add_attributes(key, flow.to_string())], + &add_attributes([(key, flow.to_string())]), ); result } @@ -35,22 +39,15 @@ where result } -pub fn add_attributes<T: Into<opentelemetry::Value>>( - key: &'static str, - value: T, -) -> opentelemetry::KeyValue { - opentelemetry::KeyValue::new(key, value) -} - -pub fn status_code_metrics(status_code: i64, flow: String, merchant_id: String) { +pub fn status_code_metrics(status_code: String, flow: String, merchant_id: String) { super::REQUEST_STATUS.add( &super::CONTEXT, 1, - &[ - add_attributes("status_code", status_code), - add_attributes("flow", flow), - add_attributes("merchant_id", merchant_id), - ], + &add_attributes([ + ("status_code", status_code), + ("flow", flow), + ("merchant_id", merchant_id), + ]), ) } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index cccbaa496e1..928b3a400eb 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -29,7 +29,7 @@ pub use hyperswitch_interfaces::api::{ BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration, ConnectorIntegrationAny, }; use masking::{Maskable, PeekInterface}; -use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag}; +use router_env::{instrument, metrics::add_attributes, tracing, tracing_actix_web::RequestId, Tag}; use serde::Serialize; use serde_json::json; use tera::{Context, Tera}; @@ -178,9 +178,9 @@ where metrics::CONNECTOR_CALL_COUNT.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes("connector", req.connector.to_string()), - metrics::request::add_attributes( + &add_attributes([ + ("connector", req.connector.to_string()), + ( "flow", std::any::type_name::<T>() .split("::") @@ -188,7 +188,7 @@ where .unwrap_or_default() .to_string(), ), - ], + ]), ); let connector_request = match connector_request { @@ -204,10 +204,7 @@ where metrics::REQUEST_BUILD_FAILURE.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - req.connector.to_string(), - )], + &add_attributes([("connector", req.connector.to_string())]), ) } error @@ -272,10 +269,10 @@ where metrics::RESPONSE_DESERIALIZATION_FAILURE.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( + &add_attributes([( "connector", req.connector.to_string(), - )], + )]), ) } error @@ -313,10 +310,7 @@ where metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "connector", - req.connector.clone(), - )], + &add_attributes([("connector", req.connector.clone())]), ); let error = match body.status_code { @@ -915,7 +909,11 @@ where ); state.event_handler().log_event(&api_event); - metrics::request::status_code_metrics(status_code, flow.to_string(), merchant_id.to_string()); + metrics::request::status_code_metrics( + status_code.to_string(), + flow.to_string(), + merchant_id.to_string(), + ); output } diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 701eda5d1c0..2aabed475b9 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -29,6 +29,7 @@ use image::Luma; use masking::ExposeInterface; use nanoid::nanoid; use qrcode; +use router_env::metrics::add_attributes; use serde::de::DeserializeOwned; use serde_json::Value; use tracing_futures::Instrument; @@ -553,12 +554,12 @@ pub async fn get_mca_from_object_reference_id( // validate json format for the error pub fn handle_json_response_deserialization_failure( res: types::Response, - connector: String, + connector: &'static str, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { metrics::RESPONSE_DESERIALIZATION_FAILURE.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes("connector", connector)], + &add_attributes([("connector", connector)]), ); let response_data = String::from_utf8(res.response.to_vec()) @@ -781,24 +782,24 @@ pub fn add_apple_pay_flow_metrics( domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( + &add_attributes([ + ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), - metrics::request::add_attributes("merchant_id", merchant_id.to_owned()), - ], + ("merchant_id", merchant_id.to_owned()), + ]), ), domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( + &add_attributes([ + ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), - metrics::request::add_attributes("merchant_id", merchant_id.to_owned()), - ], + ("merchant_id", merchant_id.to_owned()), + ]), ), } } @@ -817,26 +818,26 @@ pub fn add_apple_pay_payment_status_metrics( metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( + &add_attributes([ + ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), - metrics::request::add_attributes("merchant_id", merchant_id.to_owned()), - ], + ("merchant_id", merchant_id.to_owned()), + ]), ) } domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT .add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( + &add_attributes([ + ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), - metrics::request::add_attributes("merchant_id", merchant_id.to_owned()), - ], + ("merchant_id", merchant_id.to_owned()), + ]), ), } } @@ -847,25 +848,25 @@ pub fn add_apple_pay_payment_status_metrics( metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( + &add_attributes([ + ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), - metrics::request::add_attributes("merchant_id", merchant_id.to_owned()), - ], + ("merchant_id", merchant_id.to_owned()), + ]), ) } domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add( &metrics::CONTEXT, 1, - &[ - metrics::request::add_attributes( + &add_attributes([ + ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), - metrics::request::add_attributes("merchant_id", merchant_id.to_owned()), - ], + ("merchant_id", merchant_id.to_owned()), + ]), ), } } diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index c24671be34d..8d8f1aa6c85 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -2,7 +2,7 @@ use common_utils::{errors::ValidationError, ext_traits::ValueExt}; use diesel_models::{ enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData, }; -use router_env::logger; +use router_env::{logger, metrics::add_attributes}; use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerSessionState}; use crate::{ @@ -130,7 +130,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { metrics::TASKS_RESET_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes("flow", "ApiKeyExpiry")], + &add_attributes([("flow", "ApiKeyExpiry")]), ); } diff --git a/crates/router_env/src/metrics.rs b/crates/router_env/src/metrics.rs index e75cacaa3c9..780c010579f 100644 --- a/crates/router_env/src/metrics.rs +++ b/crates/router_env/src/metrics.rs @@ -120,3 +120,18 @@ macro_rules! gauge_metric { > = once_cell::sync::Lazy::new(|| $meter.u64_observable_gauge($description).init()); }; } + +pub use helpers::add_attributes; + +mod helpers { + pub fn add_attributes<T, U>(attributes: U) -> Vec<opentelemetry::KeyValue> + where + T: Into<opentelemetry::Value>, + U: IntoIterator<Item = (&'static str, T)>, + { + attributes + .into_iter() + .map(|(key, value)| opentelemetry::KeyValue::new(key, value)) + .collect::<Vec<_>>() + } +} diff --git a/crates/storage_impl/src/metrics.rs b/crates/storage_impl/src/metrics.rs index 2f22d578133..cb7a6b216e4 100644 --- a/crates/storage_impl/src/metrics.rs +++ b/crates/storage_impl/src/metrics.rs @@ -1,4 +1,4 @@ -use router_env::{counter_metric, global_meter, metrics_context}; +use router_env::{counter_metric, gauge_metric, global_meter, metrics_context}; metrics_context!(CONTEXT); global_meter!(GLOBAL_METER, "ROUTER_API"); @@ -11,3 +11,9 @@ 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); counter_metric!(KV_SOFT_KILL_ACTIVE_UPDATE, GLOBAL_METER); + +// Metrics for In-memory cache +gauge_metric!(IN_MEMORY_CACHE_ENTRY_COUNT, GLOBAL_METER); +counter_metric!(IN_MEMORY_CACHE_HIT, GLOBAL_METER); +counter_metric!(IN_MEMORY_CACHE_MISS, GLOBAL_METER); +counter_metric!(IN_MEMORY_CACHE_EVICTION_COUNT, GLOBAL_METER); diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 6ad96be2795..81e7e38b1be 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -9,10 +9,14 @@ use error_stack::{Report, ResultExt}; use moka::future::Cache as MokaCache; use once_cell::sync::Lazy; use redis_interface::{errors::RedisError, RedisConnectionPool, RedisValue}; -use router_env::tracing::{self, instrument}; +use router_env::{ + metrics::add_attributes, + tracing::{self, instrument}, +}; use crate::{ errors::StorageError, + metrics, redis::{PubSubInterface, RedisConnInterface}, }; @@ -53,31 +57,44 @@ const CACHE_TTI: u64 = 10 * 60; const MAX_CAPACITY: u64 = 30; /// Config Cache with time_to_live as 30 mins and time_to_idle as 10 mins. -pub static CONFIG_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, None)); +pub static CONFIG_CACHE: Lazy<Cache> = + Lazy::new(|| Cache::new("CONFIG_CACHE", CACHE_TTL, CACHE_TTI, None)); /// Accounts cache with time_to_live as 30 mins and size limit pub static ACCOUNTS_CACHE: Lazy<Cache> = - Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); + Lazy::new(|| Cache::new("ACCOUNTS_CACHE", 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))); + Lazy::new(|| Cache::new("ROUTING_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); /// 3DS Decision Manager Cache -pub static DECISION_MANAGER_CACHE: Lazy<Cache> = - Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); +pub static DECISION_MANAGER_CACHE: Lazy<Cache> = Lazy::new(|| { + Cache::new( + "DECISION_MANAGER_CACHE", + CACHE_TTL, + CACHE_TTI, + Some(MAX_CAPACITY), + ) +}); /// Surcharge Cache pub static SURCHARGE_CACHE: Lazy<Cache> = - Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); + Lazy::new(|| Cache::new("SURCHARGE_CACHE", 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))); + Lazy::new(|| Cache::new("CGRAPH_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); /// PM Filter CGraph Cache -pub static PM_FILTERS_CGRAPH_CACHE: Lazy<Cache> = - Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); +pub static PM_FILTERS_CGRAPH_CACHE: Lazy<Cache> = Lazy::new(|| { + Cache::new( + "PM_FILTERS_CGRAPH_CACHE", + 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 { @@ -150,6 +167,7 @@ where dyn_clone::clone_trait_object!(Cacheable); pub struct Cache { + name: &'static str, inner: MokaCache<String, Arc<dyn Cacheable>>, } @@ -173,19 +191,38 @@ impl From<CacheKey> for String { impl Cache { /// With given `time_to_live` and `time_to_idle` creates a moka cache. /// + /// `name` : Cache type name to be used as an attribute in metrics /// `time_to_live`: Time in seconds before an object is stored in a caching system before it’s deleted /// `time_to_idle`: Time in seconds before a `get` or `insert` operation an object is stored in a caching system before it's deleted /// `max_capacity`: Max size in MB's that the cache can hold - pub fn new(time_to_live: u64, time_to_idle: u64, max_capacity: Option<u64>) -> Self { + pub fn new( + name: &'static str, + time_to_live: u64, + time_to_idle: u64, + max_capacity: Option<u64>, + ) -> Self { + // Record the metrics of manual invalidation of cache entry by the application + let eviction_listener = move |_, _, cause| { + metrics::IN_MEMORY_CACHE_EVICTION_COUNT.add( + &metrics::CONTEXT, + 1, + &add_attributes([ + ("cache_type", name.to_owned()), + ("removal_cause", format!("{:?}", cause)), + ]), + ); + }; let mut cache_builder = MokaCache::builder() .time_to_live(std::time::Duration::from_secs(time_to_live)) - .time_to_idle(std::time::Duration::from_secs(time_to_idle)); + .time_to_idle(std::time::Duration::from_secs(time_to_idle)) + .eviction_listener(eviction_listener); if let Some(capacity) = max_capacity { cache_builder = cache_builder.max_capacity(capacity * 1024 * 1024); } Self { + name, inner: cache_builder.build(), } } @@ -195,8 +232,26 @@ impl Cache { } pub async fn get_val<T: Clone + Cacheable>(&self, key: CacheKey) -> Option<T> { - let val = self.inner.get::<String>(&key.into()).await?; - (*val).as_any().downcast_ref::<T>().cloned() + let val = self.inner.get::<String>(&key.into()).await; + + // Add cache hit and cache miss metrics + if val.is_some() { + metrics::IN_MEMORY_CACHE_HIT.add( + &metrics::CONTEXT, + 1, + &add_attributes([("cache_type", self.name)]), + ); + } else { + metrics::IN_MEMORY_CACHE_MISS.add( + &metrics::CONTEXT, + 1, + &add_attributes([("cache_type", self.name)]), + ); + } + + let val = (*val?).as_any().downcast_ref::<T>().cloned(); + + val } /// Check if a key exists in cache @@ -209,14 +264,28 @@ impl Cache { } /// Performs any pending maintenance operations needed by the cache. - pub async fn run_pending_tasks(&self) { + async fn run_pending_tasks(&self) { self.inner.run_pending_tasks().await; } /// Returns an approximate number of entries in this cache. - pub fn get_entry_count(&self) -> u64 { + fn get_entry_count(&self) -> u64 { self.inner.entry_count() } + + pub fn name(&self) -> &'static str { + self.name + } + + pub async fn record_entry_count_metric(&self) { + self.run_pending_tasks().await; + + metrics::IN_MEMORY_CACHE_ENTRY_COUNT.observe( + &metrics::CONTEXT, + self.get_entry_count(), + &add_attributes([("cache_type", self.name)]), + ); + } } #[instrument(skip_all)] @@ -390,7 +459,7 @@ mod cache_tests { #[tokio::test] async fn construct_and_get_cache() { - let cache = Cache::new(1800, 1800, None); + let cache = Cache::new("test", 1800, 1800, None); cache .push( CacheKey { @@ -413,7 +482,7 @@ mod cache_tests { #[tokio::test] async fn eviction_on_size_test() { - let cache = Cache::new(2, 2, Some(0)); + let cache = Cache::new("test", 2, 2, Some(0)); cache .push( CacheKey { @@ -436,7 +505,7 @@ mod cache_tests { #[tokio::test] async fn invalidate_cache_for_key() { - let cache = Cache::new(1800, 1800, None); + let cache = Cache::new("test", 1800, 1800, None); cache .push( CacheKey { @@ -467,7 +536,7 @@ mod cache_tests { #[tokio::test] async fn eviction_on_time_test() { - let cache = Cache::new(2, 2, None); + let cache = Cache::new("test", 2, 2, None); cache .push( CacheKey {
2024-06-13T19:17:51Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR introduces basic counter metrics for IMC - * hits (successful read) * misses (failed read) * manual invalidations (done by applications) - makes use of eviction listener on moka that can help identify strategy based evictions This PR also moves the `add_attribute` method of metrics to `router_env` crate. This method now takes a list of attributes as an argument as opposed to just one (key,value) pair. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Insert new config key value pair. Data is not cached in IMC during insertion ``` curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "key": "test_key", "value": "test_val_1" }' ``` 2. Retrieve the inserted config so that the data gets cached to IMC. Since this is the first time the data is getting retrieved, there'll be a cache mis ``` curl --location 'http://localhost:8080/configs/test_key' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/99f05a27-3ddd-4e5d-9458-f5673423ddc8) 3. Again retrieve the same config. Since in the previous retrieve, the data was cached, this retrieve will be a cache hit ``` curl --location 'http://localhost:8080/configs/test_key' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/b3ecd6da-3268-4830-be0b-7ca677f6c4d4) 4. Update the inserted config. This time the cache data has to be invalidated. This should increment the `IN_MEMORY_CACHE_EVICTION_COUNT` metric ``` curl --location 'http://localhost:8080/configs/test_key' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "key": "test_key", "value": "test_val_2" }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/d9492d34-9767-4e41-83a0-c0462af047b5) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
91c8af6ef6d74cc3e0cb55c5f26ca1eae6907709
juspay/hyperswitch
juspay__hyperswitch-5000
Bug: fix(opensearch): show search results only if user has access to the index /search and /search/{domain} are currently checking for analytics ACL before hitting opensearch and returning results. we have to change this to check access permissions per index payments attempts/intents => PaymentRead | PaymentWrite refunds => RefundRead | RefundWrite disputes => DisputeRead | DisputeWrite can modify GetSearchResponse to include status ``` enum SearchStatus = Success | Failure | NoAccess pub struct GetSearchResponse { pub count: u64, pub index: SearchIndex, pub hits: Vec<Value>, pub status: SearchStatus } ```
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index e8f87aaef2e..b8c582df1bf 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -20,7 +20,6 @@ use opensearch::{ }; use serde_json::{json, Value}; use storage_impl::errors::ApplicationError; -use strum::IntoEnumIterator; use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError}; use crate::query::QueryBuildingError; @@ -78,6 +77,10 @@ pub enum OpenSearchError { QueryBuildingError, #[error("Opensearch deserialisation error")] DeserialisationError, + #[error("Opensearch index access not present error: {0:?}")] + IndexAccessNotPermittedError(SearchIndex), + #[error("Opensearch unknown error")] + UnknownError, } impl ErrorSwitch<OpenSearchError> for QueryBuildingError { @@ -97,28 +100,39 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError { )), Self::ResponseNotOK(response) => ApiErrorResponse::InternalServerError(ApiError::new( "IR", - 0, + 1, format!("Something went wrong {}", response), None, )), Self::ResponseError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", - 0, + 2, "Something went wrong", None, )), Self::QueryBuildingError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", - 0, + 3, "Query building error", None, )), Self::DeserialisationError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", - 0, + 4, "Deserialisation error", None, )), + Self::IndexAccessNotPermittedError(index) => { + ApiErrorResponse::ForbiddenCommonResource(ApiError::new( + "IR", + 5, + format!("Index access not permitted: {index:?}"), + None, + )) + } + Self::UnknownError => { + ApiErrorResponse::InternalServerError(ApiError::new("IR", 6, "Unknown error", None)) + } } } } @@ -179,18 +193,16 @@ impl OpenSearchClient { query_builder: OpenSearchQueryBuilder, ) -> CustomResult<Response, OpenSearchError> { match query_builder.query_type { - OpenSearchQuery::Msearch => { - let search_indexes = SearchIndex::iter(); - + OpenSearchQuery::Msearch(ref indexes) => { let payload = query_builder - .construct_payload(search_indexes.clone().collect()) + .construct_payload(indexes) .change_context(OpenSearchError::QueryBuildingError)?; - let payload_with_indexes = payload.into_iter().zip(search_indexes).fold( + let payload_with_indexes = payload.into_iter().zip(indexes).fold( Vec::new(), |mut payload_with_indexes, (index_hit, index)| { payload_with_indexes.push( - json!({"index": self.search_index_to_opensearch_index(index)}).into(), + json!({"index": self.search_index_to_opensearch_index(*index)}).into(), ); payload_with_indexes.push(JsonBody::new(index_hit.clone())); payload_with_indexes @@ -207,7 +219,7 @@ impl OpenSearchClient { OpenSearchQuery::Search(index) => { let payload = query_builder .clone() - .construct_payload(vec![index]) + .construct_payload(&[index]) .change_context(OpenSearchError::QueryBuildingError)?; let final_payload = payload.first().unwrap_or(&Value::Null); @@ -349,7 +361,7 @@ pub struct OpenSearchHealth { #[derive(Debug, Clone)] pub enum OpenSearchQuery { - Msearch, + Msearch(Vec<SearchIndex>), Search(SearchIndex), } @@ -384,7 +396,7 @@ impl OpenSearchQueryBuilder { Ok(()) } - pub fn construct_payload(&self, indexes: Vec<SearchIndex>) -> QueryResult<Vec<Value>> { + pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> { let mut query = vec![json!({"multi_match": {"type": "phrase", "query": self.query, "lenient": true}})]; diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index 8810dc1e3a1..373ca3acbb6 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -1,11 +1,10 @@ use api_models::analytics::search::{ GetGlobalSearchRequest, GetSearchRequestWithIndex, GetSearchResponse, OpenMsearchOutput, - OpensearchOutput, SearchIndex, + OpensearchOutput, SearchIndex, SearchStatus, }; use common_utils::errors::{CustomResult, ReportSwitchExt}; use error_stack::ResultExt; use router_env::tracing; -use strum::IntoEnumIterator; use crate::opensearch::{ OpenSearchClient, OpenSearchError, OpenSearchQuery, OpenSearchQueryBuilder, @@ -15,8 +14,10 @@ pub async fn msearch_results( client: &OpenSearchClient, req: GetGlobalSearchRequest, merchant_id: &String, + indexes: Vec<SearchIndex>, ) -> CustomResult<Vec<GetSearchResponse>, OpenSearchError> { - let mut query_builder = OpenSearchQueryBuilder::new(OpenSearchQuery::Msearch, req.query); + let mut query_builder = + OpenSearchQueryBuilder::new(OpenSearchQuery::Msearch(indexes.clone()), req.query); query_builder .add_filter_clause("merchant_id".to_string(), merchant_id.to_string()) @@ -40,29 +41,19 @@ pub async fn msearch_results( Ok(response_body .responses .into_iter() - .zip(SearchIndex::iter()) + .zip(indexes) .map(|(index_hit, index)| match index_hit { - OpensearchOutput::Success(success) => { - if success.status == 200 { - GetSearchResponse { - count: success.hits.total.value, - index, - hits: success - .hits - .hits - .into_iter() - .map(|hit| hit.source) - .collect(), - } - } else { - tracing::error!("Unexpected status code: {}", success.status,); - GetSearchResponse { - count: 0, - index, - hits: Vec::new(), - } - } - } + OpensearchOutput::Success(success) => GetSearchResponse { + count: success.hits.total.value, + index, + hits: success + .hits + .hits + .into_iter() + .map(|hit| hit.source) + .collect(), + status: SearchStatus::Success, + }, OpensearchOutput::Error(error) => { tracing::error!( index = ?index, @@ -73,6 +64,7 @@ pub async fn msearch_results( count: 0, index, hits: Vec::new(), + status: SearchStatus::Failure, } } }) @@ -113,27 +105,17 @@ pub async fn search_results( let response_body: OpensearchOutput = response_text; match response_body { - OpensearchOutput::Success(success) => { - if success.status == 200 { - Ok(GetSearchResponse { - count: success.hits.total.value, - index: req.index, - hits: success - .hits - .hits - .into_iter() - .map(|hit| hit.source) - .collect(), - }) - } else { - tracing::error!("Unexpected status code: {}", success.status); - Ok(GetSearchResponse { - count: 0, - index: req.index, - hits: Vec::new(), - }) - } - } + OpensearchOutput::Success(success) => Ok(GetSearchResponse { + count: success.hits.total.value, + index: req.index, + hits: success + .hits + .hits + .into_iter() + .map(|hit| hit.source) + .collect(), + status: SearchStatus::Success, + }), OpensearchOutput::Error(error) => { tracing::error!( index = ?req.index, @@ -144,6 +126,7 @@ pub async fn search_results( count: 0, index: req.index, hits: Vec::new(), + status: SearchStatus::Failure, }) } } diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index c29bb0e9f71..a01349d987f 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -30,7 +30,9 @@ pub struct GetSearchRequestWithIndex { pub search_req: GetSearchRequest, } -#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)] +#[derive( + Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy, Eq, PartialEq, +)] #[serde(rename_all = "snake_case")] pub enum SearchIndex { PaymentAttempts, @@ -39,17 +41,26 @@ pub enum SearchIndex { Disputes, } +#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)] +pub enum SearchStatus { + Success, + Failure, +} + #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSearchResponse { pub count: u64, pub index: SearchIndex, pub hits: Vec<Value>, + pub status: SearchStatus, } #[derive(Debug, serde::Deserialize)] pub struct OpenMsearchOutput { + #[serde(default)] pub responses: Vec<OpensearchOutput>, + pub error: Option<OpensearchErrorDetails>, } #[derive(Debug, serde::Deserialize)] @@ -74,7 +85,6 @@ pub struct OpensearchErrorDetails { #[derive(Debug, serde::Deserialize)] pub struct OpensearchSuccess { - pub status: u16, pub hits: OpensearchHits, } diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index b471448368f..988870e8c06 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, connector_events::connector_events_core, - errors::AnalyticsError, lambda_utils::invoke_lambda, + errors::AnalyticsError, lambda_utils::invoke_lambda, opensearch::OpenSearchError, outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core, AnalyticsFlow, }; @@ -20,13 +20,14 @@ pub mod routes { use error_stack::ResultExt; use crate::{ - core::api_locking, + consts::opensearch::OPENSEARCH_INDEX_PERMISSIONS, + core::{api_locking, errors::user::UserErrors}, db::user::UserInterface, routes::AppState, services::{ api, - authentication::{self as auth, AuthenticationData}, - authorization::permissions::Permission, + authentication::{self as auth, AuthenticationData, UserFromToken}, + authorization::{permissions::Permission, roles::RoleInfo}, ApplicationResponse, }, types::domain::UserEmail, @@ -653,11 +654,25 @@ pub mod routes { state.clone(), &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req, _| async move { + |state, auth: UserFromToken, req, _| async move { + let role_id = auth.role_id; + let role_info = + RoleInfo::from_role_id(&state, &role_id, &auth.merchant_id, &auth.org_id) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)?; + let permissions = role_info.get_permissions_set(); + let accessible_indexes: Vec<_> = OPENSEARCH_INDEX_PERMISSIONS + .iter() + .filter(|(_, perm)| perm.iter().any(|p| permissions.contains(p))) + .map(|(i, _)| *i) + .collect(); + analytics::search::msearch_results( &state.opensearch_client, req, - &auth.merchant_account.merchant_id, + &auth.merchant_id, + accessible_indexes, ) .await .map(ApplicationResponse::Json) @@ -674,24 +689,33 @@ pub mod routes { json_payload: web::Json<GetSearchRequest>, index: web::Path<SearchIndex>, ) -> impl Responder { + let index = index.into_inner(); let flow = AnalyticsFlow::GetSearchResults; let indexed_req = GetSearchRequestWithIndex { search_req: json_payload.into_inner(), - index: index.into_inner(), + index, }; Box::pin(api::server_wrap( flow, state.clone(), &req, indexed_req, - |state, auth: AuthenticationData, req, _| async move { - analytics::search::search_results( - &state.opensearch_client, - req, - &auth.merchant_account.merchant_id, - ) - .await - .map(ApplicationResponse::Json) + |state, auth: UserFromToken, req, _| async move { + let role_id = auth.role_id; + let role_info = + RoleInfo::from_role_id(&state, &role_id, &auth.merchant_id, &auth.org_id) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)?; + let permissions = role_info.get_permissions_set(); + let _ = OPENSEARCH_INDEX_PERMISSIONS + .iter() + .filter(|(ind, _)| *ind == index) + .find(|i| i.1.iter().any(|p| permissions.contains(p))) + .ok_or(OpenSearchError::IndexAccessNotPermittedError(index))?; + analytics::search::search_results(&state.opensearch_client, req, &auth.merchant_id) + .await + .map(ApplicationResponse::Json) }, &auth::JWTAuth(Permission::Analytics), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 73ff7c428e4..bffc5241339 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -1,3 +1,4 @@ +pub mod opensearch; #[cfg(feature = "olap")] pub mod user; pub mod user_role; diff --git a/crates/router/src/consts/opensearch.rs b/crates/router/src/consts/opensearch.rs new file mode 100644 index 00000000000..fc1c071439a --- /dev/null +++ b/crates/router/src/consts/opensearch.rs @@ -0,0 +1,22 @@ +use api_models::analytics::search::SearchIndex; + +use crate::services::authorization::permissions::Permission; + +pub const OPENSEARCH_INDEX_PERMISSIONS: &[(SearchIndex, &[Permission])] = &[ + ( + SearchIndex::PaymentAttempts, + &[Permission::PaymentRead, Permission::PaymentWrite], + ), + ( + SearchIndex::PaymentIntents, + &[Permission::PaymentRead, Permission::PaymentWrite], + ), + ( + SearchIndex::Refunds, + &[Permission::RefundRead, Permission::RefundWrite], + ), + ( + SearchIndex::Disputes, + &[Permission::DisputeRead, Permission::DisputeWrite], + ), +]; diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index 632989c4806..1bdd9016c49 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -83,7 +83,7 @@ impl EventsConfig { impl EventsHandler { pub fn log_event<T: KafkaMessage>(&self, event: &T) { match self { - Self::Kafka(kafka) => kafka.log_event(event).map_or((), |e| { + Self::Kafka(kafka) => kafka.log_event(event).unwrap_or_else(|e| { logger::error!("Failed to log event: {:?}", e); }), Self::Logs(logger) => logger.log_event(event),
2024-06-24T09:40:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> /search and /search/{domain} are currently checking for analytics ACL before hitting opensearch and returning results. Additionally we have to check access permissions per index: - payment attempts/intents => PaymentRead | PaymentWrite - refunds => RefundRead | RefundWrite - disputes => DisputeRead | DisputeWrite ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> Checking access permissions to an index for a user is necessary to show results appropriately. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Open the dashboard locally and hit the get_global_search_results API through the global search feature (command+k). - Search using a query (eg: USD), to get the results corresponding to respective indexes (if user has access permission) - Evaluate and verify the results ![Screenshot 2024-06-24 at 2 09 09 PM](https://github.com/juspay/hyperswitch/assets/83278309/9a86540a-4e76-44db-981f-175f1520b59e) <img width="1683" alt="Screenshot 2024-06-25 at 11 26 25 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/4a50c14f-59ca-48e0-ab10-81a5208445ba"> ![Screenshot 2024-06-24 at 2 09 42 PM](https://github.com/juspay/hyperswitch/assets/83278309/44ec721a-2c38-4703-b0d2-442ac85121a7) <img width="1706" alt="Screenshot 2024-06-25 at 11 26 44 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/5123df9f-89bb-4433-85ab-b25988dd317c"> Alternatively, it can also be verified through Postman: - Hit the /search and /search/{domain} API's to retrieve the data <img width="1243" alt="Screenshot 2024-06-24 at 1 45 52 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/b00a552d-128a-4fc1-bef2-a449aa6eef0c"> <img width="1234" alt="Screenshot 2024-06-24 at 2 16 30 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/ef741c5f-d27f-435d-a86e-3c47c980b112"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
4ccd25d0dc0703f9ac9ff441bedc8a9ce4ce78c6
juspay/hyperswitch
juspay__hyperswitch-4997
Bug: [FEATURE] Use Ephemeral auth for Customer PM list and PM delete APIs ### Feature Description We want to enable Ephemeral auth for both customer's PM list and PM delete API for the SDK to be able to use these APIs in a non-payments context ### Possible Implementation Implementation would involve changing the Ephemeral auth types and auth process for the said APIs ### 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/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index 65abb012b9a..264f205c907 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -195,6 +195,7 @@ pub async fn list_customer_payment_method_api( auth.key_store, Some(req), Some(&customer_id), + None, ) }, &auth::ApiKeyAuth, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 0641c842390..62a0b65e7cf 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -64,6 +64,7 @@ use crate::{ pii::prelude::*, routes::{ self, + app::SessionStateInfo, metrics::{self, request}, payment_methods::ParentPaymentMethodToken, }, @@ -3080,10 +3081,25 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( key_store: domain::MerchantKeyStore, req: Option<api::PaymentMethodListRequest>, customer_id: Option<&id_type::CustomerId>, + ephemeral_api_key: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let db = state.store.as_ref(); let limit = req.clone().and_then(|pml_req| pml_req.limit); + let auth_cust = if let Some(key) = ephemeral_api_key { + let key = state + .store() + .get_ephemeral_key(key) + .await + .change_context(errors::ApiErrorResponse::Unauthorized)?; + + Some(key.customer_id.clone()) + } else { + None + }; + + let customer_id = customer_id.or(auth_cust.as_ref()); + if let Some(customer_id) = customer_id { Box::pin(list_customer_payment_method( &state, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 87366cf5c6d..4684edbd18d 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -47,7 +47,7 @@ pub async fn customers_retrieve( let auth = if auth::is_jwt_auth(req.headers()) { Box::new(auth::JWTAuth(Permission::CustomerRead)) } else { - match auth::is_ephemeral_auth(req.headers(), &payload.customer_id) { + match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index e36a8fc3ea5..09b5c625711 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -139,7 +139,7 @@ pub async fn list_customer_payment_method_api( let payload = query_payload.into_inner(); let customer_id = customer_id.into_inner().0; - let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), &customer_id) { + let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; @@ -155,6 +155,7 @@ pub async fn list_customer_payment_method_api( auth.key_store, Some(req), Some(&customer_id), + None, ) }, &*ephemeral_auth, @@ -194,10 +195,12 @@ pub async fn list_customer_payment_method_api_client( ) -> HttpResponse { let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); - let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { - Ok((auth, _auth_flow)) => (auth, _auth_flow), - Err(e) => return api::log_and_return_error_response(e), - }; + let api_key = auth::get_api_key(req.headers()).ok(); + let (auth, _, is_ephemeral_auth) = + match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload)).await { + Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth), + Err(e) => return api::log_and_return_error_response(e), + }; Box::pin(api::server_wrap( flow, @@ -211,6 +214,7 @@ pub async fn list_customer_payment_method_api_client( auth.key_store, Some(req), None, + is_ephemeral_auth.then_some(api_key).flatten(), ) }, &*auth, @@ -291,6 +295,11 @@ pub async fn payment_method_delete_api( let pm = PaymentMethodId { payment_method_id: payment_method_id.into_inner().0, }; + let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + Box::pin(api::server_wrap( flow, state, @@ -299,7 +308,7 @@ pub async fn payment_method_delete_api( |state, auth, req, _| { cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store) }, - &auth::ApiKeyAuth, + &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await @@ -345,7 +354,7 @@ pub async fn default_payment_method_set_api( let pc = payload.clone(); let customer_id = &pc.customer_id; - let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), customer_id) { + let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 72d0860eed9..e2224da29ea 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -5,7 +5,7 @@ use api_models::{ }; use async_trait::async_trait; use common_enums::TokenPurpose; -use common_utils::{date_time, id_type}; +use common_utils::date_time; use error_stack::{report, ResultExt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use masking::PeekInterface; @@ -440,7 +440,7 @@ where } #[derive(Debug)] -pub struct EphemeralKeyAuth(pub id_type::CustomerId); +pub struct EphemeralKeyAuth; #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth @@ -460,9 +460,6 @@ where .await .change_context(errors::ApiErrorResponse::Unauthorized)?; - if ephemeral_key.customer_id.ne(&self.0) { - return Err(report!(errors::ApiErrorResponse::InvalidEphemeralKey)); - } MerchantIdAuth(ephemeral_key.merchant_id) .authenticate_and_fetch(request_headers, state) .await @@ -1046,16 +1043,43 @@ where Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant)) } +pub async fn get_ephemeral_or_other_auth<T>( + headers: &HeaderMap, + is_merchant_flow: bool, + payload: Option<&impl ClientSecretFetch>, +) -> RouterResult<( + Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, + api::AuthFlow, + bool, +)> +where + T: SessionStateInfo, + ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, + PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, + EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, +{ + let api_key = get_api_key(headers)?; + + if api_key.starts_with("epk") { + Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true)) + } else if is_merchant_flow { + Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant, false)) + } else { + let payload = payload.get_required_value("ClientSecretFetch")?; + let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload)?; + Ok((auth, auth_flow, false)) + } +} + pub fn is_ephemeral_auth<A: SessionStateInfo + Sync>( headers: &HeaderMap, - customer_id: &id_type::CustomerId, ) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { let api_key = get_api_key(headers)?; if !api_key.starts_with("epk") { Ok(Box::new(ApiKeyAuth)) } else { - Ok(Box::new(EphemeralKeyAuth(customer_id.to_owned()))) + Ok(Box::new(EphemeralKeyAuth)) } }
2024-06-13T10:38:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR enables - - Ephemeral key auth for customer's pm list - Ephemeral key auth for delete payment method ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Save a card for a customer 2. Create Ephemeral key for that customer ``` curl --location --request POST 'http://localhost:8080/ephemeral_keys' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "customer_id": "cus_q1KVr57JhvRlVHToTKkY" }' ``` Response - ``` { "id": "eki_DuTISISBl1O0MAyczMQ8", "merchant_id": "sarthak1", "customer_id": "cus_grCxh6TyR6uepXyc6p7q", "created_at": 1718270809, "expires": 1718274409, "secret": "epk_67d4e3b46c49402badcbff4901cfef67" } ``` 3. Use the Ephemeral key secret to call customer's pm list ``` curl --location --request GET 'http://localhost:8080/customers/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: epk_be243219006647c69cdd7111d490d79a' ``` Response - ``` { "customer_payment_methods": [ { "payment_token": "token_9OtU08A46TOZcmfislqy", "payment_method_id": "pm_RPkRCYXKIWZFj0Qr36E9", "customer_id": "Some_cust1", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-06-13T09:59:16.717Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-13T09:59:16.717Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": null } ``` 4. Separate flow, Delete a PM using Ephemeral key ``` curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_RPkRCYXKIWZFj0Qr36E9' \ --header 'Accept: application/json' \ --header 'api-key: epk_be243219006647c69cdd7111d490d79a' ``` Response - ``` { "payment_method_id": "pm_RPkRCYXKIWZFj0Qr36E9", "deleted": true } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0e059e7d847b0c15ed120c72bb4902ac60e6f955
juspay/hyperswitch
juspay__hyperswitch-4992
Bug: feat(users): Decision manager changes for SSO Flows Because SSO needs new flows and will affect other login flows and email flows like accept invite, we have to change some flows in Decision Manager for SSO flows.
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index decbf9fd12a..f6d47f9a638 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2758,6 +2758,10 @@ pub enum BankHolderType { #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { + AuthSelect, + #[serde(rename = "sso")] + #[strum(serialize = "sso")] + SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 6803b79d6ce..505cee0c4ac 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1048,7 +1048,7 @@ pub async fn accept_invite_from_email_token_only_flow( .map_err(|e| logger::error!(?e)); let current_flow = domain::CurrentFlow::new( - user_token.origin, + user_token, domain::SPTFlow::AcceptInvitationFromEmail.into(), )?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; @@ -1502,8 +1502,7 @@ pub async fn verify_email_token_only_flow( .await .map_err(|e| logger::error!(?e)); - let current_flow = - domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::VerifyEmail.into())?; + let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::VerifyEmail.into())?; let next_flow = current_flow.next(user_from_db, &state).await?; let token = next_flow.get_token(&state).await?; @@ -1959,7 +1958,7 @@ pub async fn terminate_two_factor_auth( } } - let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::TOTP.into())?; + let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::TOTP.into())?; let next_flow = current_flow.next(user_from_db, &state).await?; let token = next_flow.get_token(&state).await?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index c4beb0fe9a4..9e7f676c095 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -288,7 +288,7 @@ pub async fn merchant_select_token_only_flow( .into(); let current_flow = - domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::MerchantSelect.into())?; + domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; let token = next_flow diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index e2224da29ea..675b3951806 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -124,6 +124,7 @@ impl AuthenticationType { pub struct UserFromSinglePurposeToken { pub user_id: String, pub origin: domain::Origin, + pub path: Vec<TokenPurpose>, } #[cfg(feature = "olap")] @@ -132,6 +133,7 @@ pub struct SinglePurposeToken { pub user_id: String, pub purpose: TokenPurpose, pub origin: domain::Origin, + pub path: Vec<TokenPurpose>, pub exp: u64, } @@ -142,6 +144,7 @@ impl SinglePurposeToken { purpose: TokenPurpose, origin: domain::Origin, settings: &Settings, + path: Vec<TokenPurpose>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS); @@ -151,6 +154,7 @@ impl SinglePurposeToken { purpose, origin, exp, + path, }; jwt::generate_jwt(&token_payload, settings).await } @@ -356,6 +360,7 @@ where UserFromSinglePurposeToken { user_id: payload.user_id.clone(), origin: payload.origin.clone(), + path: payload.path, }, AuthenticationType::SinglePurposeJwt { user_id: payload.user_id, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 5ff79b7feee..4ad25f003d1 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1107,6 +1107,7 @@ impl SignInWithMultipleRolesStrategy { TokenPurpose::AcceptInvite, Origin::SignIn, &state.conf, + vec![], ) .await? .into(), diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 2ee9b389788..ef73b88015f 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -17,9 +17,14 @@ pub enum UserFlow { } impl UserFlow { - async fn is_required(&self, user: &UserFromStorage, state: &SessionState) -> UserResult<bool> { + async fn is_required( + &self, + user: &UserFromStorage, + path: &[TokenPurpose], + state: &SessionState, + ) -> UserResult<bool> { match self { - Self::SPTFlow(flow) => flow.is_required(user, state).await, + Self::SPTFlow(flow) => flow.is_required(user, path, state).await, Self::JWTFlow(flow) => flow.is_required(user, state).await, } } @@ -27,6 +32,8 @@ impl UserFlow { #[derive(Eq, PartialEq, Clone, Copy)] pub enum SPTFlow { + AuthSelect, + SSO, TOTP, VerifyEmail, AcceptInvitationFromEmail, @@ -36,15 +43,26 @@ pub enum SPTFlow { } impl SPTFlow { - async fn is_required(&self, user: &UserFromStorage, state: &SessionState) -> UserResult<bool> { + async fn is_required( + &self, + user: &UserFromStorage, + path: &[TokenPurpose], + state: &SessionState, + ) -> UserResult<bool> { match self { + // Auth + // AuthSelect and SSO flow are not enabled, once the terminate SSO API is ready, we can enable these flows + Self::AuthSelect => Ok(false), + Self::SSO => Ok(false), // TOTP - Self::TOTP => Ok(true), + Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)), // Main email APIs Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true), Self::VerifyEmail => Ok(true), // Final Checks - Self::ForceSetPassword => user.is_password_rotate_required(state), + Self::ForceSetPassword => user + .is_password_rotate_required(state) + .map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)), Self::MerchantSelect => user .get_roles_from_db(state) .await @@ -62,6 +80,7 @@ impl SPTFlow { self.into(), next_flow.origin.clone(), &state.conf, + next_flow.path.to_vec(), ) .await .map(|token| token.into()) @@ -103,6 +122,8 @@ impl JWTFlow { #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum Origin { + #[serde(rename = "sign_in_with_sso")] + SignInWithSSO, SignIn, SignUp, MagicLink, @@ -114,6 +135,7 @@ pub enum Origin { impl Origin { fn get_flows(&self) -> &'static [UserFlow] { match self { + Self::SignInWithSSO => &SIGNIN_WITH_SSO_FLOW, Self::SignIn => &SIGNIN_FLOW, Self::SignUp => &SIGNUP_FLOW, Self::VerifyEmail => &VERIFY_EMAIL_FLOW, @@ -124,6 +146,11 @@ impl Origin { } } +const SIGNIN_WITH_SSO_FLOW: [UserFlow; 2] = [ + UserFlow::SPTFlow(SPTFlow::MerchantSelect), + UserFlow::JWTFlow(JWTFlow::UserInfo), +]; + const SIGNIN_FLOW: [UserFlow; 4] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), @@ -154,7 +181,9 @@ const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [ UserFlow::JWTFlow(JWTFlow::UserInfo), ]; -const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 4] = [ +const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 6] = [ + UserFlow::SPTFlow(SPTFlow::AuthSelect), + UserFlow::SPTFlow(SPTFlow::SSO), UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), @@ -169,31 +198,40 @@ const RESET_PASSWORD_FLOW: [UserFlow; 2] = [ pub struct CurrentFlow { origin: Origin, current_flow_index: usize, + path: Vec<TokenPurpose>, } impl CurrentFlow { - pub fn new(origin: Origin, current_flow: UserFlow) -> UserResult<Self> { - let flows = origin.get_flows(); + pub fn new( + token: auth::UserFromSinglePurposeToken, + current_flow: UserFlow, + ) -> UserResult<Self> { + let flows = token.origin.get_flows(); let index = flows .iter() .position(|flow| flow == &current_flow) .ok_or(UserErrors::InternalServerError)?; + let mut path = token.path; + path.push(current_flow.into()); Ok(Self { - origin, + origin: token.origin, current_flow_index: index, + path, }) } - pub async fn next(&self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> { + pub async fn next(self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> { let flows = self.origin.get_flows(); let remaining_flows = flows.iter().skip(self.current_flow_index + 1); + for flow in remaining_flows { - if flow.is_required(&user, state).await? { + if flow.is_required(&user, &self.path, state).await? { return Ok(NextFlow { origin: self.origin.clone(), next_flow: *flow, user, + path: self.path, }); } } @@ -205,6 +243,7 @@ pub struct NextFlow { origin: Origin, next_flow: UserFlow, user: UserFromStorage, + path: Vec<TokenPurpose>, } impl NextFlow { @@ -214,12 +253,14 @@ impl NextFlow { state: &SessionState, ) -> UserResult<Self> { let flows = origin.get_flows(); + let path = vec![]; for flow in flows { - if flow.is_required(&user, state).await? { + if flow.is_required(&user, &path, state).await? { return Ok(Self { origin, next_flow: *flow, user, + path, }); } } @@ -284,6 +325,8 @@ impl From<UserFlow> for TokenPurpose { impl From<SPTFlow> for TokenPurpose { fn from(value: SPTFlow) -> Self { match value { + SPTFlow::AuthSelect => Self::AuthSelect, + SPTFlow::SSO => Self::SSO, SPTFlow::TOTP => Self::TOTP, SPTFlow::VerifyEmail => Self::VerifyEmail, SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail,
2024-06-13T10:36:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds SSO flows in login decision flows. Currently they are disabled as we have no APIs for SSO and will be enabled in upcoming PRs which adds SSO APIs. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 #4992. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - There should be no changes in any of the flows. - SPT changes can be tested as follows: 1. Generate SPT using any of the token only APIs (I am using Sign in) ```curl curl --location 'http://localhost:8080/user/v2/signin?token_only=true' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY4YzFmZTQtODRiMC00Y2NjLWI4NGYtN2VjYmVkNjg5Y2Q5IiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcxODg3MzYyN30.HK_0mcCyvbFwh-nma48Pbeh2kdkO7s3FsVOtIc6UF9w", "token_type": "totp" } ``` 2. Complete the next step ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: SPT with Purpose as `totp`' \ ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMzBkOGVkYTEtOWM2ZC00MjgwLTg3MDgtN2MwMjBjY2U1ZmNkIiwicHVycG9zZSI6ImFjY2VwdF9pbnZpdGF0aW9uX2Zyb21fZW1haWwiLCJvcmlnaW4iOiJhY2NlcHRfaW52aXRhdGlvbl9mcm9tX2VtYWlsIiwicGF0aCI6WyJ0b3RwIl0sImV4cCI6MTcxODg3OTQ3OH0.tLsVZ-kYbaxaXaq3Jn4-kJ0ghswonTCjbclUrWZLeoc", "token_type": "accept_invitation_from_email" } ``` The above token when decoded (using [this](https://jwt.io/)), it should have the `path` field with the step that has been completed. And the SPT body will look something like this: ``` { "user_id": "30d8eda1-9c6d-4280-8708-7c020cce5fcd", "purpose": "accept_invitation_from_email", "origin": "accept_invitation_from_email", "path": [ "totp" ], "exp": 1718879478 } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e658899c1406225bb905ce4fb76e13fa3609666e
juspay/hyperswitch
juspay__hyperswitch-4987
Bug: bug(events): api events with event_type `user` aren't parsed correctly in clickhouse The api events with events type user aren't parsed correctly in the user table, this happens due to there being duplicate keys in the json representation which is treated as invalid json by clickhouse ```json { "key_a": "abc", "key_b": "def", "key_b": "ghi" } ``` This is treated as invalid json and the entire event is dropped by clickhouse, in this case we have ```rs pub enum ApiEventsType { ......... User { merchant_id: String, // This merchant_id field ends up being duplicate and causes invalid json user_id: String, }, ...... } ``` for now we can remove the merchant_id from this enum variant to solve this issue
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index c41f52a93ea..287bafaace8 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -24,7 +24,6 @@ use crate::user::{ impl ApiEventMetric for DashboardEntryResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::User { - merchant_id: self.merchant_id.clone(), user_id: self.user_id.clone(), }) } @@ -34,7 +33,6 @@ impl ApiEventMetric for DashboardEntryResponse { 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(), }) } diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 1052840dbc8..ef5502d8b5b 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -29,8 +29,6 @@ pub enum ApiEventsType { customer_id: id_type::CustomerId, }, User { - //specified merchant_id will overridden on global defined - merchant_id: String, user_id: String, }, PaymentMethodList { diff --git a/docker-compose.yml b/docker-compose.yml index d16f946a6e5..57f7ccde1cd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -378,6 +378,8 @@ services: - "8123:8123" volumes: - ./crates/analytics/docs/clickhouse/scripts:/docker-entrypoint-initdb.d + environment: + - TZ=Asia/Kolkata profiles: - olap ulimits:
2024-06-18T11:02:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description fix(events): Correct parsing of API events with user event_type for ClickHouse (#4987) - Removed redundant `merchant_id` to handle user events correctly in ClickHouse. - Updated Docker Compose to display times in IST timezone for ClickHouse. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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). --> ## How did you test it? By switching the merchant from localhost dashboard itself. ![image](https://github.com/juspay/hyperswitch/assets/89402434/22394100-d35e-4ec2-8cef-94f1ac2a8e84) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d76ce2beaedcc09351dcfb70e27940c42a31c35d
juspay/hyperswitch
juspay__hyperswitch-5027
Bug: feat(connector): [DATATRANS] add Connector Payment Flows Code Implemented Card Payments for Datatrans
diff --git a/config/development.toml b/config/development.toml index b3548b35d06..4965723fb76 100644 --- a/config/development.toml +++ b/config/development.toml @@ -191,7 +191,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" -datatrans.base_url = "https://api.sandbox.datatrans.com" +datatrans.base_url = "https://api.sandbox.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 29d344dfd5a..62e976b0933 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -90,7 +90,7 @@ pub enum Connector { Coinbase, Cryptopay, Cybersource, - // Datatrans, + Datatrans, Dlocal, Ebanx, Fiserv, @@ -257,7 +257,7 @@ impl Connector { | Self::Razorpay | Self::Riskified | Self::Threedsecureio - // | Self::Datatrans + | Self::Datatrans | Self::Netcetera | Self::Noon | Self::Stripe => false, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 87d4f5e775a..850c6666548 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -132,7 +132,7 @@ pub enum RoutableConnectors { Coinbase, Cryptopay, Cybersource, - // Datatrans, + Datatrans, Dlocal, Ebanx, Fiserv, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index baa606f82c1..e0ecbcb8797 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -156,6 +156,7 @@ pub struct ConnectorConfig { pub iatapay: Option<ConnectorTomlConfig>, pub opennode: Option<ConnectorTomlConfig>, pub bambora: Option<ConnectorTomlConfig>, + pub datatrans: Option<ConnectorTomlConfig>, pub dlocal: Option<ConnectorTomlConfig>, pub ebanx_payout: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, @@ -290,6 +291,7 @@ impl ConnectorConfig { Connector::Iatapay => Ok(connector_data.iatapay), Connector::Opennode => Ok(connector_data.opennode), Connector::Bambora => Ok(connector_data.bambora), + Connector::Datatrans => Ok(connector_data.datatrans), Connector::Dlocal => Ok(connector_data.dlocal), Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Fiserv => Ok(connector_data.fiserv), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index e62e8d8ea48..f3755e83bfb 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -2797,4 +2797,45 @@ three_ds_requestor_id="ThreeDS request id" payment_method_type = "UnionPay" [billwerk.connector_auth.BodyKey] api_key="Private Api Key" -key1="Public Api Key" \ No newline at end of file +key1="Public Api Key" + +[datatrans] +[[datatrans.credit]] + payment_method_type = "Mastercard" +[[datatrans.credit]] + payment_method_type = "Visa" +[[datatrans.credit]] + payment_method_type = "Interac" +[[datatrans.credit]] + payment_method_type = "AmericanExpress" +[[datatrans.credit]] + payment_method_type = "JCB" +[[datatrans.credit]] + payment_method_type = "DinersClub" +[[datatrans.credit]] + payment_method_type = "Discover" +[[datatrans.credit]] + payment_method_type = "CartesBancaires" +[[datatrans.credit]] + payment_method_type = "UnionPay" +[[datatrans.debit]] + payment_method_type = "Mastercard" +[[datatrans.debit]] + payment_method_type = "Visa" +[[datatrans.debit]] + payment_method_type = "Interac" +[[datatrans.debit]] + payment_method_type = "AmericanExpress" +[[datatrans.debit]] + payment_method_type = "JCB" +[[datatrans.debit]] + payment_method_type = "DinersClub" +[[datatrans.debit]] + payment_method_type = "Discover" +[[datatrans.debit]] + payment_method_type = "CartesBancaires" +[[datatrans.debit]] + payment_method_type = "UnionPay" +[datatrans.connector_auth.BodyKey] +api_key = "Passcode" +key1 = "datatrans MerchantId" \ No newline at end of file diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index c31b75ad3fc..33c3c4a60d9 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -2026,4 +2026,45 @@ key1 = "Merchant ID" payment_method_type = "UnionPay" [billwerk.connector_auth.BodyKey] api_key="Private Api Key" -key1="Public Api Key" \ No newline at end of file +key1="Public Api Key" + +[datatrans] +[[datatrans.credit]] + payment_method_type = "Mastercard" +[[datatrans.credit]] + payment_method_type = "Visa" +[[datatrans.credit]] + payment_method_type = "Interac" +[[datatrans.credit]] + payment_method_type = "AmericanExpress" +[[datatrans.credit]] + payment_method_type = "JCB" +[[datatrans.credit]] + payment_method_type = "DinersClub" +[[datatrans.credit]] + payment_method_type = "Discover" +[[datatrans.credit]] + payment_method_type = "CartesBancaires" +[[datatrans.credit]] + payment_method_type = "UnionPay" +[[datatrans.debit]] + payment_method_type = "Mastercard" +[[datatrans.debit]] + payment_method_type = "Visa" +[[datatrans.debit]] + payment_method_type = "Interac" +[[datatrans.debit]] + payment_method_type = "AmericanExpress" +[[datatrans.debit]] + payment_method_type = "JCB" +[[datatrans.debit]] + payment_method_type = "DinersClub" +[[datatrans.debit]] + payment_method_type = "Discover" +[[datatrans.debit]] + payment_method_type = "CartesBancaires" +[[datatrans.debit]] + payment_method_type = "UnionPay" +[datatrans.connector_auth.BodyKey] +api_key = "Passcode" +key1 = "datatrans MerchantId" \ No newline at end of file diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 5b44dc1551d..1ae9fc665b2 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -2799,3 +2799,44 @@ three_ds_requestor_id="ThreeDS request id" [billwerk.connector_auth.BodyKey] api_key="Private Api Key" key1="Public Api Key" + +[datatrans] +[[datatrans.credit]] + payment_method_type = "Mastercard" +[[datatrans.credit]] + payment_method_type = "Visa" +[[datatrans.credit]] + payment_method_type = "Interac" +[[datatrans.credit]] + payment_method_type = "AmericanExpress" +[[datatrans.credit]] + payment_method_type = "JCB" +[[datatrans.credit]] + payment_method_type = "DinersClub" +[[datatrans.credit]] + payment_method_type = "Discover" +[[datatrans.credit]] + payment_method_type = "CartesBancaires" +[[datatrans.credit]] + payment_method_type = "UnionPay" +[[datatrans.debit]] + payment_method_type = "Mastercard" +[[datatrans.debit]] + payment_method_type = "Visa" +[[datatrans.debit]] + payment_method_type = "Interac" +[[datatrans.debit]] + payment_method_type = "AmericanExpress" +[[datatrans.debit]] + payment_method_type = "JCB" +[[datatrans.debit]] + payment_method_type = "DinersClub" +[[datatrans.debit]] + payment_method_type = "Discover" +[[datatrans.debit]] + payment_method_type = "CartesBancaires" +[[datatrans.debit]] + payment_method_type = "UnionPay" +[datatrans.connector_auth.BodyKey] +api_key = "Passcode" +key1 = "datatrans MerchantId" \ No newline at end of file diff --git a/crates/router/src/connector/datatrans.rs b/crates/router/src/connector/datatrans.rs index 90c6b38d2fb..9c7772c5b3e 100644 --- a/crates/router/src/connector/datatrans.rs +++ b/crates/router/src/connector/datatrans.rs @@ -1,13 +1,15 @@ pub mod transformers; - -use std::fmt::Debug; - +use api_models::enums::{CaptureMethod, PaymentMethodType}; +use base64::Engine; +use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; use error_stack::{report, ResultExt}; -use masking::ExposeInterface; -use transformers as datatrans; +use masking::PeekInterface; +use transformers::{self as datatrans}; +use super::{utils as connector_utils, utils::RefundsRequestData}; use crate::{ configs::settings, + consts, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, @@ -24,9 +26,6 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Datatrans; - impl api::Payment for Datatrans {} impl api::PaymentSession for Datatrans {} impl api::ConnectorAccessToken for Datatrans {} @@ -40,6 +39,19 @@ impl api::RefundExecute for Datatrans {} impl api::RefundSync for Datatrans {} impl api::PaymentToken for Datatrans {} +#[derive(Clone)] +pub struct Datatrans { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Datatrans { + pub const fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} + impl ConnectorIntegration< api::PaymentMethodToken, @@ -92,9 +104,11 @@ impl ConnectorCommon for Datatrans { ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = datatrans::DatatransAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let auth_key = format!("{}:{}", auth.merchant_id.peek(), auth.passcode.peek()); + let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), + auth_header.into_masked(), )]) } @@ -110,12 +124,11 @@ impl ConnectorCommon for Datatrans { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response.error.code, + message: response.error.message.clone(), + reason: Some(response.error.message.clone()), attempt_status: None, connector_transaction_id: None, }) @@ -124,6 +137,23 @@ impl ConnectorCommon for Datatrans { impl ConnectorValidation for Datatrans { //TODO: implement functions when support enabled + fn validate_capture_method( + &self, + capture_method: Option<CaptureMethod>, + _pmt: Option<PaymentMethodType>, + ) -> CustomResult<(), errors::ConnectorError> { + let capture_method = capture_method.unwrap_or_default(); + match capture_method { + CaptureMethod::Automatic | CaptureMethod::Manual => Ok(()), + CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => { + Err(errors::ConnectorError::NotSupported { + message: capture_method.to_string(), + connector: self.id(), + } + .into()) + } + } + } } impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> @@ -164,9 +194,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, _req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let base_url = self.base_url(connectors); + Ok(format!("{base_url}v1/transactions/authorize")) } fn get_request_body( @@ -174,12 +205,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = datatrans::DatatransRouterData::try_from(( - &self.get_currency_unit(), + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = datatrans::DatatransRouterData::try_from((amount, req))?; let connector_req = datatrans::DatatransPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -212,7 +243,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: datatrans::DatatransPaymentsResponse = res + let response: datatrans::DatatransResponse = res .response .parse_struct("Datatrans PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -251,10 +282,16 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - _req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + let base_url = self.base_url(connectors); + Ok(format!("{base_url}v1/transactions/{connector_payment_id}")) } fn build_request( @@ -278,9 +315,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - let response: datatrans::DatatransPaymentsResponse = res + let response: datatrans::DatatransSyncResponse = res .response - .parse_struct("datatrans PaymentsSyncResponse") + .parse_struct("datatrans DatatransSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -317,18 +354,29 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req.request.connector_transaction_id.clone(); + let base_url = self.base_url(connectors); + Ok(format!( + "{base_url}v1/transactions/{connector_payment_id}/settle" + )) } fn get_request_body( &self, - _req: &types::PaymentsCaptureRouterData, + req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, + req.request.currency, + )?; + let connector_router_data = datatrans::DatatransRouterData::try_from((amount, req))?; + let connector_req = datatrans::DataPaymentCaptureRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -357,10 +405,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { - let response: datatrans::DatatransPaymentsResponse = res - .response - .parse_struct("Datatrans PaymentsCaptureResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let response = if res.response.is_empty() { + datatrans::DataTransCaptureResponse::Empty + } else { + res.response + .parse_struct("Datatrans DataTransCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + }; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { @@ -382,6 +433,74 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Datatrans { + fn get_headers( + &self, + req: &types::PaymentsCancelRouterData, + 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::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let transaction_id = req.request.connector_transaction_id.clone(); + let base_url = self.base_url(connectors); + Ok(format!("{base_url}v1/transactions/{transaction_id}/cancel")) + } + + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(types::PaymentsVoidType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response = if res.response.is_empty() { + datatrans::DataTransCancelResponse::Empty + } else { + res.response + .parse_struct("Datatrans DataTransCancelResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + }; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> @@ -401,10 +520,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let transaction_id = req.request.connector_transaction_id.clone(); + let base_url = self.base_url(connectors); + Ok(format!("{base_url}v1/transactions/{transaction_id}/credit")) } fn get_request_body( @@ -412,12 +533,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = datatrans::DatatransRouterData::try_from(( - &self.get_currency_unit(), + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + let connector_router_data = datatrans::DatatransRouterData::try_from((amount, req))?; let connector_req = datatrans::DatatransRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -447,11 +568,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - let response: datatrans::RefundResponse = res + let response: datatrans::DatatransRefundsResponse = res .response - .parse_struct("datatrans RefundResponse") + .parse_struct("datatrans DatatransRefundsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, @@ -486,10 +608,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - _req: &types::RefundSyncRouterData, - _connectors: &settings::Connectors, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_refund_id = req.request.get_connector_refund_id()?; + let base_url = self.base_url(connectors); + Ok(format!("{base_url}v1/transactions/{connector_refund_id}")) } fn build_request( @@ -516,9 +640,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - let response: datatrans::RefundResponse = res + let response: datatrans::DatatransSyncResponse = res .response - .parse_struct("datatrans RefundSyncResponse") + .parse_struct("datatrans DatatransSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs index b079708e233..bb8c85b77da 100644 --- a/crates/router/src/connector/datatrans/transformers.rs +++ b/crates/router/src/connector/datatrans/transformers.rs @@ -1,24 +1,149 @@ +use std::fmt::Debug; + +use common_utils::types::MinorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::PaymentsAuthorizeRequestData, + connector::{ + utils as connector_utils, + utils::{PaymentsAuthorizeRequestData, RouterData}, + }, core::errors, - types::{self, api, domain, storage::enums}, + types::{ + self, + api::{self, enums}, + domain, + transformers::ForeignFrom, + }, }; -//TODO: Fill the struct with respective fields +const TRANSACTION_ALREADY_CANCELLED: &str = "transaction already canceled"; +const TRANSACTION_ALREADY_SETTLED: &str = "already settled"; + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct DatatransErrorResponse { + pub error: DatatransError, +} +pub struct DatatransAuthType { + pub(super) merchant_id: Secret<String>, + pub(super) passcode: Secret<String>, +} + pub struct DatatransRouterData<T> { - pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: MinorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for DatatransRouterData<T> { +#[derive(Debug, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct DatatransPaymentsRequest { + pub amount: MinorUnit, + pub currency: enums::Currency, + pub card: PlainCardDetails, + pub refno: String, + pub auto_settle: bool, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum TransactionType { + Payment, + Credit, + CardCheck, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum TransactionStatus { + Initialized, + Authenticated, + Authorized, + Settled, + Canceled, + Transmitted, + Failed, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum DatatransSyncResponse { + Error(DatatransError), + Response(SyncResponse), +} +#[derive(Debug, Deserialize, Serialize)] +pub enum DataTransCaptureResponse { + Error(DatatransError), + Empty, +} + +#[derive(Debug, Deserialize, Serialize)] +pub enum DataTransCancelResponse { + Error(DatatransError), + Empty, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct SyncResponse { + pub transaction_id: String, + #[serde(rename = "type")] + pub res_type: TransactionType, + pub status: TransactionStatus, +} + +#[derive(Serialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct PlainCardDetails { + #[serde(rename = "type")] + pub res_type: String, + pub number: cards::CardNumber, + pub expiry_month: Secret<String>, + pub expiry_year: Secret<String>, +} + +#[derive(Debug, Clone, Serialize, Default, Deserialize)] +pub struct DatatransError { + pub code: String, + pub message: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DatatransResponse { + TransactionResponse(DatatransSuccessResponse), + ErrorResponse(DatatransError), +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DatatransSuccessResponse { + pub transaction_id: String, + pub acquirer_authorization_code: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DatatransRefundsResponse { + Success(DatatransSuccessResponse), + Error(DatatransError), +} + +#[derive(Default, Debug, Serialize)] +pub struct DatatransRefundRequest { + pub amount: MinorUnit, + pub currency: enums::Currency, + pub refno: String, +} + +#[derive(Debug, Serialize, Clone)] +pub struct DataPaymentCaptureRequest { + pub amount: MinorUnit, + pub currency: enums::Currency, + pub refno: String, +} + +impl<T> TryFrom<(MinorUnit, T)> for DatatransRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), - ) -> Result<Self, Self::Error> { - //Todo : use utils to convert the amount to the type of amount that a connector accepts + fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, @@ -26,22 +151,6 @@ impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for DatatransRout } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct DatatransPaymentsRequest { - amount: i64, - card: DatatransCard, -} - -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct DatatransCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, -} - impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> for DatatransPaymentsRequest { @@ -49,108 +158,162 @@ impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> fn try_from( item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { + if item.router_data.is_three_ds() { + return Err(errors::ConnectorError::NotImplemented( + "Three_ds payments through Datatrans".to_string(), + ) + .into()); + }; match item.router_data.request.payment_method_data.clone() { - domain::PaymentMethodData::Card(req_card) => { - let card = DatatransCard { + domain::PaymentMethodData::Card(req_card) => Ok(Self { + amount: item.amount, + currency: item.router_data.request.currency, + card: PlainCardDetails { + res_type: "PLAIN".to_string(), number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, - cvc: req_card.card_cvc, - complete: item.router_data.request.is_auto_capture()?, - }; - Ok(Self { - amount: item.amount.to_owned(), - card, - }) + }, + refno: item.router_data.connector_request_reference_id.clone(), + auto_settle: matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) + ), + }), + domain::PaymentMethodData::Wallet(_) + | domain::PaymentMethodData::PayLater(_) + | domain::PaymentMethodData::BankRedirect(_) + | domain::PaymentMethodData::BankDebit(_) + | domain::PaymentMethodData::BankTransfer(_) + | domain::PaymentMethodData::Crypto(_) + | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::Reward + | domain::PaymentMethodData::RealTimePayment(_) + | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::CardRedirect(_) + | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + connector_utils::get_unimplemented_payment_method_error_message("Datatrans"), + ))? } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } - -//TODO: Fill the struct with respective fields -// Auth Struct -pub struct DatatransAuthType { - pub(super) api_key: Secret<String>, -} - impl TryFrom<&types::ConnectorAuthType> for DatatransAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: api_key.to_owned(), + types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + merchant_id: key1.clone(), + passcode: api_key.clone(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum DatatransPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, -} -impl From<DatatransPaymentStatus> for enums::AttemptStatus { - fn from(item: DatatransPaymentStatus) -> Self { +impl ForeignFrom<(&DatatransResponse, bool)> for enums::AttemptStatus { + fn foreign_from((item, is_auto_capture): (&DatatransResponse, bool)) -> Self { match item { - DatatransPaymentStatus::Succeeded => Self::Charged, - DatatransPaymentStatus::Failed => Self::Failure, - DatatransPaymentStatus::Processing => Self::Authorizing, + DatatransResponse::ErrorResponse(_) => Self::Failure, + DatatransResponse::TransactionResponse(_) => { + if is_auto_capture { + Self::Charged + } else { + Self::Authorized + } + } + } + } +} +impl From<SyncResponse> for enums::AttemptStatus { + fn from(item: SyncResponse) -> Self { + match item.res_type { + TransactionType::Payment => match item.status { + TransactionStatus::Authorized => Self::Authorized, + TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Charged, + TransactionStatus::Canceled => Self::Voided, + TransactionStatus::Failed => Self::Failure, + TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending, + }, + TransactionType::Credit | TransactionType::CardCheck => Self::Failure, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct DatatransPaymentsResponse { - status: DatatransPaymentStatus, - id: String, +impl From<SyncResponse> for enums::RefundStatus { + fn from(item: SyncResponse) -> Self { + match item.res_type { + TransactionType::Credit => match item.status { + TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Success, + TransactionStatus::Initialized + | TransactionStatus::Authenticated + | TransactionStatus::Authorized + | TransactionStatus::Canceled + | TransactionStatus::Failed => Self::Failure, + }, + TransactionType::Payment | TransactionType::CardCheck => Self::Failure, + } + } } -impl<F, T> - TryFrom<types::ResponseRouterData<F, DatatransPaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F> + TryFrom< + types::ResponseRouterData< + F, + DatatransResponse, + 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, - DatatransPaymentsResponse, - T, + DatatransResponse, + types::PaymentsAuthorizeData, 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), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - incremental_authorization_allowed: None, - charge_id: None, + let status = enums::AttemptStatus::foreign_from(( + &item.response, + item.data.request.is_auto_capture()?, + )); + let response = match &item.response { + DatatransResponse::ErrorResponse(error) => Err(types::ErrorResponse { + code: error.code.clone(), + message: error.message.clone(), + reason: Some(error.message.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, }), + DatatransResponse::TransactionResponse(response) => { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response.transaction_id.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }) + } + }; + Ok(Self { + status, + response, ..item.data }) } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct DatatransRefundRequest { - pub amount: i64, -} - impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for DatatransRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( @@ -158,78 +321,191 @@ impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for Datatran ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + refno: item.router_data.request.refund_id.clone(), }) } } -// Type definition for Refund Response +impl TryFrom<types::RefundsResponseRouterData<api::Execute, DatatransRefundsResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, DatatransRefundsResponse>, + ) -> Result<Self, Self::Error> { + match item.response { + DatatransRefundsResponse::Error(error) => Ok(Self { + response: Err(types::ErrorResponse { + code: error.code.clone(), + message: error.message.clone(), + reason: Some(error.message), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ..item.data + }), + DatatransRefundsResponse::Success(response) => Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: response.transaction_id, + refund_status: enums::RefundStatus::Success, + }), + ..item.data + }), + } + } +} -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, +impl TryFrom<types::RefundsResponseRouterData<api::RSync, DatatransSyncResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, DatatransSyncResponse>, + ) -> Result<Self, Self::Error> { + let response = match item.response { + DatatransSyncResponse::Error(error) => Err(types::ErrorResponse { + code: error.code.clone(), + message: error.message.clone(), + reason: Some(error.message), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + DatatransSyncResponse::Response(response) => Ok(types::RefundsResponseData { + connector_refund_id: response.transaction_id.to_string(), + refund_status: enums::RefundStatus::from(response), + }), + }; + Ok(Self { + response, + ..item.data + }) + } } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { - match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping +impl TryFrom<types::PaymentsSyncResponseRouterData<DatatransSyncResponse>> + for types::PaymentsSyncRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::PaymentsSyncResponseRouterData<DatatransSyncResponse>, + ) -> Result<Self, Self::Error> { + match item.response { + DatatransSyncResponse::Error(error) => { + let response = Err(types::ErrorResponse { + code: error.code.clone(), + message: error.message.clone(), + reason: Some(error.message), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }); + Ok(Self { + response, + ..item.data + }) + } + DatatransSyncResponse::Response(response) => { + let resource_id = + types::ResponseId::ConnectorTransactionId(response.transaction_id.to_string()); + Ok(Self { + status: enums::AttemptStatus::from(response), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id, + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +impl TryFrom<&DatatransRouterData<&types::PaymentsCaptureRouterData>> + for DataPaymentCaptureRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &DatatransRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount, + currency: item.router_data.request.currency, + refno: item.router_data.connector_request_reference_id.clone(), + }) + } } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> +impl TryFrom<types::PaymentsCaptureResponseRouterData<DataTransCaptureResponse>> + for types::PaymentsCaptureRouterData { type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: types::PaymentsCaptureResponseRouterData<DataTransCaptureResponse>, ) -> Result<Self, Self::Error> { + let status = match item.response { + DataTransCaptureResponse::Error(error) => { + if error.message == *TRANSACTION_ALREADY_SETTLED { + common_enums::AttemptStatus::Charged + } else { + common_enums::AttemptStatus::Failure + } + } + // Datatrans http code 204 implies Successful Capture + //https://api-reference.datatrans.ch/#tag/v1transactions/operation/settle + DataTransCaptureResponse::Empty => { + if item.http_code == 204 { + common_enums::AttemptStatus::Charged + } else { + common_enums::AttemptStatus::Failure + } + } + }; Ok(Self { - response: Ok(types::RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), - }), + status, ..item.data }) } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> +impl TryFrom<types::PaymentsCancelResponseRouterData<DataTransCancelResponse>> + for types::PaymentsCancelRouterData { type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: types::PaymentsCancelResponseRouterData<DataTransCancelResponse>, ) -> Result<Self, Self::Error> { + let status = match item.response { + // Datatrans http code 204 implies Successful Cancellation + //https://api-reference.datatrans.ch/#tag/v1transactions/operation/cancel + DataTransCancelResponse::Empty => { + if item.http_code == 204 { + common_enums::AttemptStatus::Voided + } else { + common_enums::AttemptStatus::Failure + } + } + DataTransCancelResponse::Error(error) => { + if error.message == *TRANSACTION_ALREADY_CANCELLED { + common_enums::AttemptStatus::Voided + } else { + common_enums::AttemptStatus::Failure + } + } + }; Ok(Self { - response: Ok(types::RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), - }), + status, ..item.data }) } } - -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] -pub struct DatatransErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, -} diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index dc72ec2ba89..5f082625eeb 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2220,11 +2220,10 @@ pub(crate) fn validate_auth_and_metadata_type_with_connector( cybersource::transformers::CybersourceAuthType::try_from(val)?; Ok(()) } - // api_enums::Connector::Datatrans => { - // datatrans::transformers::DatatransAuthType::try_from(val)?; - // Ok(()) - // } - // added for future use + api_enums::Connector::Datatrans => { + datatrans::transformers::DatatransAuthType::try_from(val)?; + Ok(()) + } api_enums::Connector::Dlocal => { dlocal::transformers::DlocalAuthType::try_from(val)?; Ok(()) diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs index b54838e5258..5528db77153 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -620,6 +620,7 @@ default_imp_for_new_connector_integration_payment!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -703,6 +704,7 @@ default_imp_for_new_connector_integration_refund!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -781,6 +783,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -881,6 +884,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -963,6 +967,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1029,6 +1034,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1122,6 +1128,7 @@ default_imp_for_new_connector_integration_file_upload!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1197,6 +1204,7 @@ default_imp_for_new_connector_integration_payouts!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1282,6 +1290,7 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1367,6 +1376,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1452,6 +1462,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1537,6 +1548,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1622,6 +1634,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1707,6 +1720,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1792,6 +1806,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1875,6 +1890,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1950,6 +1966,7 @@ default_imp_for_new_connector_integration_frm!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2035,6 +2052,7 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2120,6 +2138,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2205,6 +2224,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2290,6 +2310,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2375,6 +2396,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2457,6 +2479,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2567,6 +2590,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 443ca00f24f..c93cdb80022 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -388,6 +388,9 @@ impl ConnectorData { enums::Connector::Cybersource => { Ok(ConnectorEnum::Old(Box::new(&connector::Cybersource))) } + enums::Connector::Datatrans => { + Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new()))) + } enums::Connector::Dlocal => Ok(ConnectorEnum::Old(Box::new(&connector::Dlocal))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new( diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index b06599769f4..4b937a68139 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -239,7 +239,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Coinbase => Self::Coinbase, api_enums::Connector::Cryptopay => Self::Cryptopay, api_enums::Connector::Cybersource => Self::Cybersource, - // api_enums::Connector::Datatrans => Self::Datatrans, added as template code for future use + api_enums::Connector::Datatrans => Self::Datatrans, api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Fiserv => Self::Fiserv, diff --git a/postman/collection-json/datatrans.postman_collection.json b/postman/collection-json/datatrans.postman_collection.json new file mode 100644 index 00000000000..a0c5175623b --- /dev/null +++ b/postman/collection-json/datatrans.postman_collection.json @@ -0,0 +1,3869 @@ +{ + "info": { + "_postman_id": "600681c5-58d0-4009-b0ec-9c72b9fa14f9", + "name": "Datatrans", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "29167164" + }, + "item": [ + { + "name": "Health check", + "item": [] + }, + { + "name": "Flow Testcases", + "item": [ + { + "name": "QuickStart", + "item": [ + { + "name": "Merchant Account - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id", + "if (jsonData?.merchant_id) {", + " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);", + " console.log(", + " \"- use {{merchant_id}} as collection variable for value\",", + " jsonData.merchant_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", + "if (jsonData?.api_key) {", + " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", + " console.log(", + " \"- use {{api_key}} as collection variable for value\",", + " jsonData.api_key,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", + "if (jsonData?.publishable_key) {", + " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", + " console.log(", + " \"- use {{publishable_key}} as collection variable for value\",", + " jsonData.publishable_key,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"merchant_id\":\"postman_merchant_GHAction_{{$guid}}\",\"locker_id\":\"m0010\",\"merchant_name\":\"Braintree Merchant\",\"primary_business_details\":[{\"country\":\"US\",\"business\":\"default\"}],\"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://duck.com/success\",\"webhook_details\":{\"webhook_version\":\"1.0.1\",\"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\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/accounts", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts" + ] + }, + "description": "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments." + }, + "response": [] + }, + { + "name": "API Key - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/api_keys/:merchant_id - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", + "if (jsonData?.key_id) {", + " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", + " console.log(", + " \"- use {{api_key_id}} as collection variable for value\",", + " jsonData.key_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", + "if (jsonData?.api_key) {", + " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", + " console.log(", + " \"- use {{api_key}} as collection variable for value\",", + " jsonData.api_key,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"name\":\"API Key 1\",\"description\":null,\"expiration\":\"2069-09-23T01:02:03.000Z\"}" + }, + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Payment Connector - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(", + " \"[POST]::/account/:account_id/connectors - Status code is 2xx\",", + " function () {", + " pm.response.to.be.success;", + " },", + ");", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/account/:account_id/connectors - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", + "if (jsonData?.merchant_connector_id) {", + " pm.collectionVariables.set(", + " \"merchant_connector_id\",", + " jsonData.merchant_connector_id,", + " );", + " console.log(", + " \"- use {{merchant_connector_id}} as collection variable for value\",", + " jsonData.merchant_connector_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"datatrans\",\n \"connector_account_details\": {\n \"auth_type\": \"BodyKey\",\n \"key1\": \"{{merchantId}}\",\n \"api_key\": \"{{passcode}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"debit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc." + }, + "response": [] + }, + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 16000,\n \"currency\": \"USD\",\n \"confirm\": true, \n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 16000,\n \"customer_id\": \"First Customer\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"debit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"5127880999999990\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// Validate if response has JSON Body", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + }, + { + "name": "Payment-Capture", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"amount_to_capture\": 6540,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/capture", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "capture" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Refunds - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", + "if (jsonData?.refund_id) {", + " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": 600,\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds" + ] + }, + "description": "To create a refund against an already processed payment" + }, + "response": [] + } + ] + }, + { + "name": "Happy Cases", + "item": [ + { + "name": "Scenario 1 - Create payment with confirm true", + "item": [ + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"processing\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6541,\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"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\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"processing\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + } + ] + }, + { + "name": "Scenario 2 - Create payment with confirm false", + "item": [ + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"requires_confirmation\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6542,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"BraintreeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"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\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Confirm", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"processing\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{publishable_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"client_secret\":\"{{client_secret}}\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/confirm", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" + }, + "response": [] + }, + { + "name": "Payments - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"processing\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + } + ] + }, + { + "name": "Scenario 3 - Create payment without PMD", + "item": [ + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"requires_payment_method\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6543,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"BraintreeCustomer1\",\"email\":\"guest1@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Confirm", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"processing\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{publishable_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/confirm", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" + }, + "response": [] + }, + { + "name": "Payments - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"processing\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + } + ] + }, + { + "name": "Scenario 4 - Void the payment", + "item": [ + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"requires_capture\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6544,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"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\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Cancel", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Disabling this for now since there's an issue with cancelling a payment in the code", + "// Validate status 2xx", + "// pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {", + "// pm.response.to.be.success;", + "// });", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"cancelled\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"cancelled\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"cancellation_reason\":\"requested_by_customer\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/cancel", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "cancel" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action" + }, + "response": [] + }, + { + "name": "Payments - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Disabling this for now since there's an issue with cancelling a payment in the code", + "// Response body should have value \"cancelled\" for \"status\"", + "// if (jsonData?.status) {", + "// pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\", function() {", + "// pm.expect(jsonData.status).to.eql(\"cancelled\");", + "// })};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + } + ] + } + ] + }, + { + "name": "Variation Cases", + "item": [ + { + "name": "Scenario 1 - Create payment with Invalid card details", + "item": [ + { + "name": "Payments - Create(Invalid card number)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have \"error\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function () {", + " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'error.type' matches 'connector_error'\",", + " function () {", + " pm.expect(jsonData.error.type).to.eql(\"connector_error\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 8600,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"3423322\",\n \"card_exp_month\": \"06\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\":\"232\"\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Create(Invalid Exp month)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function () {", + " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;", + "});", + "", + "// Response body should have value \"invalid_request error\" for \"error type\"", + "if (jsonData?.error?.type) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",", + " function () {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6548,\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"13\",\"card_exp_year\":\"2023\",\"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\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Create(Invalid Exp Year)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function () {", + " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;", + "});", + "", + "// Response body should have value \"invalid_request error\" for \"error type\"", + "if (jsonData?.error?.type) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",", + " function () {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6549,\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"19990\",\"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\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Create(invalid CVV)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have \"error\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function () {", + " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;", + "});", + "", + "// Response body should have value \"invalid_request error\" for \"error type\"", + "if (jsonData?.error?.type) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",", + " function () {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6550,\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4217651111111119\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"12345\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + } + ] + }, + { + "name": "Scenario 2 - Confirming the payment without PMD", + "item": [ + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"requires_payment_method\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6551,\"currency\":\"USD\",\"confirm\":false,\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Confirm", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have \"error\"", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",", + " function () {", + " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",", + " function () {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{publishable_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"client_secret\":\"{{client_secret}}\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/confirm", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" + }, + "response": [] + } + ] + }, + { + "name": "Scenario 3 - Void the success_slash_failure payment", + "item": [ + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"processing\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6552,\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"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\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Cancel", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/payments/:id/cancel - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have \"error\"", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",", + " function () {", + " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",", + " function () {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"cancellation_reason\":\"requested_by_customer\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/cancel", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "cancel" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action" + }, + "response": [] + } + ] + }, + { + "name": "Scenario 4 - Create a payment with greater capture", + "item": [ + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"requires_capture\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6553,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"guest@example.com\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4444090101010103\",\n \"card_exp_month\": \"06\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\":\"232\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"PiX\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"PiX\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}\n\n", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"requires_capture\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_capture'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + }, + { + "name": "Payments - Capture", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/capture - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have \"error\"", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",", + " function () {", + " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",", + " function () {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount_to_capture\":7540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/capture", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "capture" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To capture the funds for an uncaptured payment" + }, + "response": [] + } + ] + } + ] + }, + { + "name": "Refunds", + "item": [ + { + "name": "Refunds - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", + "if (jsonData?.refund_id) {", + " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": 600,\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds" + ] + }, + "description": "To create a refund against an already processed payment" + }, + "response": [] + }, + { + "name": "Refunds - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/refunds/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/refunds/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", + "if (jsonData?.refund_id) {", + " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"reason\": \"Paid by mistake\",\n \"metadata\": {\n \"udf1\": \"value2\",\n \"new_customer\": \"false\",\n \"login_date\": \"2019-09-1T10:11:12Z\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{refund_id}}", + "description": "(Required) unique refund id" + } + ] + }, + "description": "To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields" + }, + "response": [] + }, + { + "name": "Refunds - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", + "if (jsonData?.refund_id) {", + " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + " console.log(\"- use {{refund_id}} as collection variable for value\",jsonData.refund_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/refunds/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{refund_id}}", + "description": "(Required) unique refund id" + } + ] + }, + "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + } + ] + } + ] + } + ], + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"[LOG]::payment_id - \" + jsonData.payment_id);", + "}", + "", + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "" + ] + } + } + ], + "variable": [ + { + "key": "baseUrl", + "value": "http://localhost:8080", + "type": "string" + }, + { + "key": "admin_api_key", + "value": "test_admin", + "type": "string" + }, + { + "key": "api_key", + "value": "", + "type": "string" + }, + { + "key": "merchant_id", + "value": "" + }, + { + "key": "payment_id", + "value": "" + }, + { + "key": "customer_id", + "value": "" + }, + { + "key": "mandate_id", + "value": "" + }, + { + "key": "payment_method_id", + "value": "" + }, + { + "key": "refund_id", + "value": "" + }, + { + "key": "merchant_connector_id", + "value": "" + }, + { + "key": "client_secret", + "value": "", + "type": "string" + }, + { + "key": "publishable_key", + "value": "", + "type": "string" + }, + { + "key": "api_key_id", + "value": "", + "type": "string" + }, + { + "key": "payment_token", + "value": "" + }, + { + "key": "gateway_merchant_id", + "value": "", + "type": "string" + }, + { + "key": "certificate", + "value": "", + "type": "string" + }, + { + "key": "certificate_keys", + "value": "", + "type": "string" + }, + { + "key": "merchantId", + "value": "1110017152", + "type": "string" + }, + { + "key": "passcode", + "value": "CJVCttkfcmB0DZJP", + "type": "string" + } + ] +} \ No newline at end of file
2024-06-18T12:14:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implemented Card Payments for Datatrans ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context https://github.com/juspay/hyperswitch/issues/5027 ## How did you test it? Attached Postman Collection `postman/collection-json/datatrans.postman_collection.json` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
3312e787f9873d10114e6a4ca78a0c3714ab2b1c
juspay/hyperswitch
juspay__hyperswitch-4998
Bug: feat(users): add schema and apis for org authentication methods Setup table and end points for org authentication methods - This will be used to support SSO login - Orgs can also setup multiple other authentication methods
diff --git a/config/config.example.toml b/config/config.example.toml index 332ab4bc00b..9bdf0b80723 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -644,4 +644,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant + +[user_auth_methods] +encryption_key = "" # Encryption key used for encrypting data in user_authentication_methods table diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 162444c9098..ccb26042f56 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -259,4 +259,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} + +[user_auth_methods] +encryption_key = "user_auth_table_encryption_key" # Encryption key used for encrypting data in user_authentication_methods table diff --git a/config/development.toml b/config/development.toml index c2f87720678..29f693f6bf2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -654,3 +654,6 @@ global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} + +[user_auth_methods] +encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 328dd30520b..1b0538d1af0 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -507,4 +507,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} + +[user_auth_methods] +encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F" diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 287bafaace8..e5d217cd8ea 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -11,14 +11,15 @@ use crate::user::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, }, AcceptInviteFromEmailRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, - ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse, - ForgotPasswordRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, - GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest, - RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, - SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, - TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse, - UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest, - VerifyRecoveryCodeRequest, VerifyTotpRequest, + ConnectAccountRequest, CreateInternalUserRequest, CreateUserAuthenticationMethodRequest, + DashboardEntryResponse, ForgotPasswordRequest, GetUserAuthenticationMethodsRequest, + GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, + InviteUserRequest, ListUsersResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, + RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest, + SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, + TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, + UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, + VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -77,7 +78,10 @@ common_utils::impl_misc_api_event_type!( BeginTotpResponse, VerifyRecoveryCodeRequest, VerifyTotpRequest, - RecoveryCodes + RecoveryCodes, + GetUserAuthenticationMethodsRequest, + CreateUserAuthenticationMethodRequest, + UpdateUserAuthenticationMethodRequest ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index a61b9fd7dff..6d567e7dca1 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -280,3 +280,78 @@ pub struct VerifyRecoveryCodeRequest { pub struct RecoveryCodes { pub recovery_codes: Vec<Secret<String>>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(tag = "auth_type")] +#[serde(rename_all = "snake_case")] +pub enum AuthConfig { + OpenIdConnect { + private_config: OpenIdConnectPrivateConfig, + public_config: OpenIdConnectPublicConfig, + }, + MagicLink, + Password, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct OpenIdConnectPrivateConfig { + pub base_url: String, + pub client_id: Secret<String>, + pub client_secret: Secret<String>, + pub private_key: Option<Secret<String>>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct OpenIdConnectPublicConfig { + pub name: OpenIdProvider, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(rename_all = "snake_case")] +pub enum OpenIdProvider { + Okta, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct OpenIdConnect { + pub name: OpenIdProvider, + pub base_url: String, + pub client_id: String, + pub client_secret: Secret<String>, + pub private_key: Option<Secret<String>>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct CreateUserAuthenticationMethodRequest { + pub owner_id: String, + pub owner_type: common_enums::Owner, + pub auth_method: AuthConfig, + pub allow_signup: bool, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct UpdateUserAuthenticationMethodRequest { + pub id: String, + // TODO: When adding more fields make config and new fields option + pub auth_method: AuthConfig, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct GetUserAuthenticationMethodsRequest { + pub auth_id: String, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct UserAuthenticationMethodResponse { + pub id: String, + pub auth_id: String, + pub auth_method: AuthMethodDetails, + pub allow_signup: bool, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct AuthMethodDetails { + #[serde(rename = "type")] + pub auth_type: common_enums::UserAuthType, + pub name: Option<OpenIdProvider>, +} diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index f3a3b02155d..decbf9fd12a 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2768,3 +2768,45 @@ pub enum TokenPurpose { AcceptInvite, UserInfo, } + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum UserAuthType { + OpenIdConnect, + MagicLink, + #[default] + Password, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum Owner { + Organization, + Tenant, + Internal, +} diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index d7d10569f7f..36dec7dde5c 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -44,6 +44,7 @@ pub mod routing_algorithm; #[allow(unused_qualifications)] pub mod schema; pub mod user; +pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 335c2db916d..9fbdf53554f 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -36,5 +36,6 @@ pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod user; +pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; diff --git a/crates/diesel_models/src/query/user_authentication_method.rs b/crates/diesel_models/src/query/user_authentication_method.rs new file mode 100644 index 00000000000..08ea6556b82 --- /dev/null +++ b/crates/diesel_models/src/query/user_authentication_method.rs @@ -0,0 +1,60 @@ +use diesel::{associations::HasTable, ExpressionMethods}; + +use crate::{ + query::generics, schema::user_authentication_methods::dsl, user_authentication_method::*, + PgPooledConn, StorageResult, +}; + +impl UserAuthenticationMethodNew { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserAuthenticationMethod> { + generics::generic_insert(conn, self).await + } +} + +impl UserAuthenticationMethod { + pub async fn list_user_authentication_methods_for_auth_id( + conn: &PgPooledConn, + auth_id: &str, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::auth_id.eq(auth_id.to_owned()), + None, + None, + Some(dsl::last_modified_at.asc()), + ) + .await + } + + pub async fn list_user_authentication_methods_for_owner_id( + conn: &PgPooledConn, + owner_id: &str, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::owner_id.eq(owner_id.to_owned()), + None, + None, + Some(dsl::last_modified_at.asc()), + ) + .await + } + + pub async fn update_user_authentication_method( + conn: &PgPooledConn, + id: &str, + user_authentication_method_update: UserAuthenticationMethodUpdate, + ) -> StorageResult<Self> { + generics::generic_update_with_unique_predicate_get_result::< + <Self as HasTable>::Table, + _, + _, + _, + >( + conn, + dsl::id.eq(id.to_owned()), + OrgAuthenticationMethodUpdateInternal::from(user_authentication_method_update), + ) + .await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 08d8f423b72..5d796444d7f 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1172,6 +1172,29 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + user_authentication_methods (id) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + auth_id -> Varchar, + #[max_length = 64] + owner_id -> Varchar, + #[max_length = 64] + owner_type -> Varchar, + #[max_length = 64] + auth_type -> Varchar, + private_config -> Nullable<Bytea>, + public_config -> Nullable<Jsonb>, + allow_signup -> Bool, + created_at -> Timestamp, + last_modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1270,6 +1293,7 @@ diesel::allow_tables_to_appear_in_same_query!( reverse_lookup, roles, routing_algorithm, + user_authentication_methods, user_key_store, user_roles, users, diff --git a/crates/diesel_models/src/user_authentication_method.rs b/crates/diesel_models/src/user_authentication_method.rs new file mode 100644 index 00000000000..2b4ed23c1d8 --- /dev/null +++ b/crates/diesel_models/src/user_authentication_method.rs @@ -0,0 +1,65 @@ +use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use time::PrimitiveDateTime; + +use crate::{encryption::Encryption, enums, schema::user_authentication_methods}; + +#[derive(Clone, Debug, Identifiable, Queryable)] +#[diesel(table_name = user_authentication_methods)] +pub struct UserAuthenticationMethod { + pub id: String, + pub auth_id: String, + pub owner_id: String, + pub owner_type: enums::Owner, + pub auth_type: enums::UserAuthType, + pub private_config: Option<Encryption>, + pub public_config: Option<serde_json::Value>, + pub allow_signup: bool, + pub created_at: PrimitiveDateTime, + pub last_modified_at: PrimitiveDateTime, +} + +#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] +#[diesel(table_name = user_authentication_methods)] +pub struct UserAuthenticationMethodNew { + pub id: String, + pub auth_id: String, + pub owner_id: String, + pub owner_type: enums::Owner, + pub auth_type: enums::UserAuthType, + pub private_config: Option<Encryption>, + pub public_config: Option<serde_json::Value>, + pub allow_signup: bool, + pub created_at: PrimitiveDateTime, + pub last_modified_at: PrimitiveDateTime, +} + +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[diesel(table_name = user_authentication_methods)] +pub struct OrgAuthenticationMethodUpdateInternal { + pub private_config: Option<Encryption>, + pub public_config: Option<serde_json::Value>, + pub last_modified_at: PrimitiveDateTime, +} + +pub enum UserAuthenticationMethodUpdate { + UpdateConfig { + private_config: Option<Encryption>, + public_config: Option<serde_json::Value>, + }, +} + +impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInternal { + fn from(value: UserAuthenticationMethodUpdate) -> Self { + let last_modified_at = common_utils::date_time::now(); + match value { + UserAuthenticationMethodUpdate::UpdateConfig { + private_config, + public_config, + } => Self { + private_config, + public_config, + last_modified_at, + }, + } + } +} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 2f90833905e..1ad65c363b0 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -220,6 +220,22 @@ impl SecretsHandler for settings::Secrets { } } +#[async_trait::async_trait] +impl SecretsHandler for settings::UserAuthMethodSettings { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let user_auth_methods = value.get_inner(); + + let encryption_key = secret_management_client + .get_secret(user_auth_methods.encryption_key.clone()) + .await?; + + Ok(value.transition_state(|_| Self { encryption_key })) + } +} + /// # Panics /// /// Will panic even if kms decryption fails for at least one field @@ -302,6 +318,14 @@ pub(crate) async fn fetch_raw_secrets( .await .expect("Failed to decrypt payment method auth configs"); + #[allow(clippy::expect_used)] + let user_auth_methods = settings::UserAuthMethodSettings::convert_to_raw_secret( + conf.user_auth_methods, + secret_management_client, + ) + .await + .expect("Failed to decrypt user_auth_methods configs"); + Settings { server: conf.server, master_database, @@ -368,5 +392,6 @@ pub(crate) async fn fetch_raw_secrets( unmasked_headers: conf.unmasked_headers, saved_payment_methods: conf.saved_payment_methods, multitenancy: conf.multitenancy, + user_auth_methods, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index daba006a56c..9e345315e98 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -123,6 +123,7 @@ pub struct Settings<S: SecretState> { pub unmasked_headers: UnmaskedHeaders, pub multitenancy: Multitenancy, pub saved_payment_methods: EligiblePaymentMethods, + pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>, } #[derive(Debug, Deserialize, Clone, Default)] @@ -615,6 +616,11 @@ pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct UserAuthMethodSettings { + pub encryption_key: Secret<String>, +} + impl Settings<SecuredSecret> { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 865bc1d4124..28b80e16cc0 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -80,6 +80,12 @@ pub enum UserErrors { TwoFactorAuthNotSetup, #[error("TOTP secret not found")] TotpSecretNotFound, + #[error("User auth method already exists")] + UserAuthMethodAlreadyExists, + #[error("Invalid user auth method operation")] + InvalidUserAuthMethodOperation, + #[error("Auth config parsing error")] + AuthConfigParsingError, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -204,6 +210,15 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::TotpSecretNotFound => { AER::BadRequest(ApiError::new(sub_code, 42, self.get_error_message(), None)) } + Self::UserAuthMethodAlreadyExists => { + AER::BadRequest(ApiError::new(sub_code, 43, self.get_error_message(), None)) + } + Self::InvalidUserAuthMethodOperation => { + AER::BadRequest(ApiError::new(sub_code, 44, self.get_error_message(), None)) + } + Self::AuthConfigParsingError => { + AER::BadRequest(ApiError::new(sub_code, 45, self.get_error_message(), None)) + } } } } @@ -247,6 +262,9 @@ impl UserErrors { Self::TwoFactorAuthRequired => "Two factor auth required", Self::TwoFactorAuthNotSetup => "Two factor auth not setup", Self::TotpSecretNotFound => "TOTP secret not found", + Self::UserAuthMethodAlreadyExists => "User auth method already exists", + Self::InvalidUserAuthMethodOperation => "Invalid user auth method operation", + Self::AuthConfigParsingError => "Auth config parsing error", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 7e79e9e2e89..6803b79d6ce 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,11 +1,13 @@ use std::collections::HashMap; use api_models::user::{self as user_api, InviteMultipleUserResponse}; +use common_utils::ext_traits::ValueExt; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; use diesel_models::{ enums::{TotpStatus, UserStatus}, user as storage_user, + user_authentication_method::{UserAuthenticationMethodNew, UserAuthenticationMethodUpdate}, user_role::UserRoleNew, }; use error_stack::{report, ResultExt}; @@ -884,7 +886,7 @@ pub async fn resend_invite( if e.current_context().is_db_not_found() { e.change_context(UserErrors::InvalidRoleOperation) .attach_printable(format!( - "User role with user_id = {} and org_id = {} is not found", + "User role with user_id = {} and merchant_id = {} is not found", user.get_user_id(), user_from_token.merchant_id )) @@ -1982,3 +1984,184 @@ pub async fn check_two_factor_auth_status( }, )) } + +pub async fn create_user_authentication_method( + state: SessionState, + req: user_api::CreateUserAuthenticationMethodRequest, +) -> UserResponse<()> { + let user_auth_encryption_key = hex::decode( + state + .conf + .user_auth_methods + .get_inner() + .encryption_key + .clone() + .expose(), + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to decode DEK")?; + + let (private_config, public_config) = match req.auth_method { + user_api::AuthConfig::OpenIdConnect { + ref private_config, + ref public_config, + } => { + let private_config_value = serde_json::to_value(private_config.clone()) + .change_context(UserErrors::AuthConfigParsingError) + .attach_printable("Failed to convert auth config to json")?; + + let encrypted_config = domain::types::encrypt::<serde_json::Value, masking::WithType>( + private_config_value.into(), + &user_auth_encryption_key, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to encrypt auth config")?; + + Ok::<_, error_stack::Report<UserErrors>>(( + Some(encrypted_config.into()), + Some( + serde_json::to_value(public_config.clone()) + .change_context(UserErrors::AuthConfigParsingError) + .attach_printable("Failed to convert auth config to json")?, + ), + )) + } + _ => Ok((None, None)), + }?; + + let auth_methods = state + .store + .list_user_authentication_methods_for_owner_id(&req.owner_id) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get list of auth methods for the owner id")?; + + let auth_id = auth_methods + .first() + .map(|auth_method| auth_method.auth_id.clone()) + .unwrap_or(uuid::Uuid::new_v4().to_string()); + + let now = common_utils::date_time::now(); + state + .store + .insert_user_authentication_method(UserAuthenticationMethodNew { + id: uuid::Uuid::new_v4().to_string(), + auth_id, + owner_id: req.owner_id, + owner_type: req.owner_type, + auth_type: req.auth_method.foreign_into(), + private_config, + public_config, + allow_signup: req.allow_signup, + created_at: now, + last_modified_at: now, + }) + .await + .to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists)?; + + Ok(ApplicationResponse::StatusOk) +} + +pub async fn update_user_authentication_method( + state: SessionState, + req: user_api::UpdateUserAuthenticationMethodRequest, +) -> UserResponse<()> { + let user_auth_encryption_key = hex::decode( + state + .conf + .user_auth_methods + .get_inner() + .encryption_key + .clone() + .expose(), + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to decode DEK")?; + + let (private_config, public_config) = match req.auth_method { + user_api::AuthConfig::OpenIdConnect { + ref private_config, + ref public_config, + } => { + let private_config_value = serde_json::to_value(private_config.clone()) + .change_context(UserErrors::AuthConfigParsingError) + .attach_printable("Failed to convert auth config to json")?; + + let encrypted_config = domain::types::encrypt::<serde_json::Value, masking::WithType>( + private_config_value.into(), + &user_auth_encryption_key, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to encrypt auth config")?; + + Ok::<_, error_stack::Report<UserErrors>>(( + Some(encrypted_config.into()), + Some( + serde_json::to_value(public_config.clone()) + .change_context(UserErrors::AuthConfigParsingError) + .attach_printable("Failed to convert auth config to json")?, + ), + )) + } + _ => Ok((None, None)), + }?; + + state + .store + .update_user_authentication_method( + &req.id, + UserAuthenticationMethodUpdate::UpdateConfig { + private_config, + public_config, + }, + ) + .await + .change_context(UserErrors::InvalidUserAuthMethodOperation)?; + Ok(ApplicationResponse::StatusOk) +} + +pub async fn list_user_authentication_methods( + state: SessionState, + req: user_api::GetUserAuthenticationMethodsRequest, +) -> UserResponse<Vec<user_api::UserAuthenticationMethodResponse>> { + let user_authentication_methods = state + .store + .list_user_authentication_methods_for_auth_id(&req.auth_id) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::Json( + user_authentication_methods + .into_iter() + .map(|auth_method| { + let auth_name = match (auth_method.auth_type, auth_method.public_config) { + (common_enums::UserAuthType::OpenIdConnect, Some(config)) => { + let open_id_public_config: user_api::OpenIdConnectPublicConfig = config + .parse_value("OpenIdConnectPublicConfig") + .change_context(UserErrors::InternalServerError) + .attach_printable("unable to parse generic data value")?; + + Ok(Some(open_id_public_config.name)) + } + (common_enums::UserAuthType::OpenIdConnect, None) => { + Err(UserErrors::InternalServerError) + .attach_printable("No config found for open_id_connect auth_method") + } + _ => Ok(None), + }?; + + Ok(user_api::UserAuthenticationMethodResponse { + id: auth_method.id, + auth_id: auth_method.auth_id, + auth_method: user_api::AuthMethodDetails { + name: auth_name, + auth_type: auth_method.auth_type, + }, + allow_signup: auth_method.allow_signup, + }) + }) + .collect::<UserResult<_>>()?, + )) +} diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index b1a00c33dfb..2bf80827e8a 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -32,6 +32,7 @@ pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod user; +pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; @@ -117,6 +118,7 @@ pub trait StorageInterface: + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface + role::RoleInterface + + user_authentication_method::UserAuthenticationMethodInterface + authentication::AuthenticationInterface + 'static { diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index ca36a53418c..2964fd78bce 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -33,6 +33,7 @@ use super::{ dashboard_metadata::DashboardMetadataInterface, role::RoleInterface, user::{sample_data::BatchSampleDataInterface, UserInterface}, + user_authentication_method::UserAuthenticationMethodInterface, user_key_store::UserKeyStoreInterface, user_role::UserRoleInterface, }; @@ -2874,3 +2875,43 @@ impl UserKeyStoreInterface for KafkaStore { .await } } + +#[async_trait::async_trait] +impl UserAuthenticationMethodInterface for KafkaStore { + async fn insert_user_authentication_method( + &self, + user_authentication_method: storage::UserAuthenticationMethodNew, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + self.diesel_store + .insert_user_authentication_method(user_authentication_method) + .await + } + + async fn list_user_authentication_methods_for_auth_id( + &self, + auth_id: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { + self.diesel_store + .list_user_authentication_methods_for_auth_id(auth_id) + .await + } + + async fn list_user_authentication_methods_for_owner_id( + &self, + owner_id: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { + self.diesel_store + .list_user_authentication_methods_for_owner_id(owner_id) + .await + } + + async fn update_user_authentication_method( + &self, + id: &str, + user_authentication_method_update: storage::UserAuthenticationMethodUpdate, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + self.diesel_store + .update_user_authentication_method(id, user_authentication_method_update) + .await + } +} diff --git a/crates/router/src/db/user_authentication_method.rs b/crates/router/src/db/user_authentication_method.rs new file mode 100644 index 00000000000..5b9aa5da8c9 --- /dev/null +++ b/crates/router/src/db/user_authentication_method.rs @@ -0,0 +1,197 @@ +use diesel_models::user_authentication_method::{self as storage}; +use error_stack::report; +use router_env::{instrument, tracing}; + +use super::MockDb; +use crate::{ + connection, + core::errors::{self, CustomResult}, + services::Store, +}; + +#[async_trait::async_trait] +pub trait UserAuthenticationMethodInterface { + async fn insert_user_authentication_method( + &self, + user_authentication_method: storage::UserAuthenticationMethodNew, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; + + async fn list_user_authentication_methods_for_auth_id( + &self, + auth_id: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; + + async fn list_user_authentication_methods_for_owner_id( + &self, + owner_id: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; + + async fn update_user_authentication_method( + &self, + id: &str, + user_authentication_method_update: storage::UserAuthenticationMethodUpdate, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; +} + +#[async_trait::async_trait] +impl UserAuthenticationMethodInterface for Store { + #[instrument(skip_all)] + async fn insert_user_authentication_method( + &self, + user_authentication_method: storage::UserAuthenticationMethodNew, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + user_authentication_method + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn list_user_authentication_methods_for_auth_id( + &self, + auth_id: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::UserAuthenticationMethod::list_user_authentication_methods_for_auth_id( + &conn, auth_id, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn list_user_authentication_methods_for_owner_id( + &self, + owner_id: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::UserAuthenticationMethod::list_user_authentication_methods_for_owner_id( + &conn, owner_id, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn update_user_authentication_method( + &self, + id: &str, + user_authentication_method_update: storage::UserAuthenticationMethodUpdate, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::UserAuthenticationMethod::update_user_authentication_method( + &conn, + id, + user_authentication_method_update, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } +} + +#[async_trait::async_trait] +impl UserAuthenticationMethodInterface for MockDb { + async fn insert_user_authentication_method( + &self, + user_authentication_method: storage::UserAuthenticationMethodNew, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + let mut user_authentication_methods = self.user_authentication_methods.lock().await; + let existing_auth_id = user_authentication_methods + .iter() + .find(|uam| uam.owner_id == user_authentication_method.owner_id) + .map(|uam| uam.auth_id.clone()); + + let auth_id = existing_auth_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); + let user_authentication_method = storage::UserAuthenticationMethod { + id: uuid::Uuid::new_v4().to_string(), + auth_id, + owner_id: user_authentication_method.auth_id, + owner_type: user_authentication_method.owner_type, + auth_type: user_authentication_method.auth_type, + public_config: user_authentication_method.public_config, + private_config: user_authentication_method.private_config, + allow_signup: user_authentication_method.allow_signup, + created_at: user_authentication_method.created_at, + last_modified_at: user_authentication_method.last_modified_at, + }; + + user_authentication_methods.push(user_authentication_method.clone()); + Ok(user_authentication_method) + } + + async fn list_user_authentication_methods_for_auth_id( + &self, + auth_id: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { + let user_authentication_methods = self.user_authentication_methods.lock().await; + + let user_authentication_methods_list: Vec<_> = user_authentication_methods + .iter() + .filter(|auth_method_inner| auth_method_inner.auth_id == auth_id) + .cloned() + .collect(); + if user_authentication_methods_list.is_empty() { + return Err(errors::StorageError::ValueNotFound(format!( + "No user authentication method found for auth_id = {}", + auth_id + )) + .into()); + } + + Ok(user_authentication_methods_list) + } + + async fn list_user_authentication_methods_for_owner_id( + &self, + owner_id: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { + let user_authentication_methods = self.user_authentication_methods.lock().await; + + let user_authentication_methods_list: Vec<_> = user_authentication_methods + .iter() + .filter(|auth_method_inner| auth_method_inner.owner_id == owner_id) + .cloned() + .collect(); + if user_authentication_methods_list.is_empty() { + return Err(errors::StorageError::ValueNotFound(format!( + "No user authentication method found for owner_id = {}", + owner_id + )) + .into()); + } + + Ok(user_authentication_methods_list) + } + + async fn update_user_authentication_method( + &self, + id: &str, + user_authentication_method_update: storage::UserAuthenticationMethodUpdate, + ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { + let mut user_authentication_methods = self.user_authentication_methods.lock().await; + user_authentication_methods + .iter_mut() + .find(|auth_method_inner| auth_method_inner.id == id) + .map(|auth_method_inner| { + *auth_method_inner = match user_authentication_method_update { + storage::UserAuthenticationMethodUpdate::UpdateConfig { + private_config, + public_config, + } => storage::UserAuthenticationMethod { + private_config, + public_config, + last_modified_at: common_utils::date_time::now(), + ..auth_method_inner.to_owned() + }, + }; + auth_method_inner.to_owned() + }) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No authentication method available for the id = {id}" + )) + .into(), + ) + } +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 2e7a6c4f61e..d4aebc3adc4 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1377,6 +1377,18 @@ impl User { ), ); + route = route.service( + web::scope("/auth") + .service( + web::resource("") + .route(web::post().to(create_user_authentication_method)) + .route(web::put().to(update_user_authentication_method)), + ) + .service( + web::resource("/list").route(web::get().to(list_user_authentication_methods)), + ), + ); + #[cfg(feature = "email")] { route = route diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index a64343757b5..72017411783 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -223,7 +223,10 @@ impl From<Flow> for ApiIdentifier { | Flow::RecoveryCodeVerify | Flow::RecoveryCodesGenerate | Flow::TerminateTwoFactorAuth - | Flow::TwoFactorAuthStatus => Self::User, + | Flow::TwoFactorAuthStatus + | Flow::CreateUserAuthenticationMethod + | Flow::UpdateUserAuthenticationMethod + | Flow::ListUserAuthenticationMethods => Self::User, Flow::ListRoles | Flow::GetRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 5325cbe437b..f297e41e4e0 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -749,3 +749,60 @@ pub async fn check_two_factor_auth_status( )) .await } + +pub async fn create_user_authentication_method( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::CreateUserAuthenticationMethodRequest>, +) -> HttpResponse { + let flow = Flow::CreateUserAuthenticationMethod; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, _, req_body, _| user_core::create_user_authentication_method(state, req_body), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn update_user_authentication_method( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::UpdateUserAuthenticationMethodRequest>, +) -> HttpResponse { + let flow = Flow::UpdateUserAuthenticationMethod; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, _, req_body, _| user_core::update_user_authentication_method(state, req_body), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn list_user_authentication_methods( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<user_api::GetUserAuthenticationMethodsRequest>, +) -> HttpResponse { + let flow = Flow::ListUserAuthenticationMethods; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + query.into_inner(), + |state, _, req, _| user_core::list_user_authentication_methods(state, req), + &auth::NoAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index f5626c267d2..5a358c272b1 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -35,6 +35,7 @@ pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod user; +pub mod user_authentication_method; pub mod user_role; use std::collections::HashMap; @@ -62,7 +63,7 @@ pub use self::{ file::*, fraud_check::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, user::*, - user_role::*, + user_authentication_method::*, user_role::*, }; use crate::types::api::routing; diff --git a/crates/router/src/types/storage/user_authentication_method.rs b/crates/router/src/types/storage/user_authentication_method.rs new file mode 100644 index 00000000000..87856f38052 --- /dev/null +++ b/crates/router/src/types/storage/user_authentication_method.rs @@ -0,0 +1 @@ +pub use diesel_models::user_authentication_method::*; diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 3792da49e84..25c851549d1 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -13,7 +13,10 @@ use crate::{ authentication::{AuthToken, UserFromToken}, authorization::roles::RoleInfo, }, - types::domain::{self, MerchantAccount, UserFromStorage}, + types::{ + domain::{self, MerchantAccount, UserFromStorage}, + transformers::ForeignFrom, + }, }; pub mod dashboard_metadata; @@ -200,3 +203,13 @@ pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnect .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get redis connection") } + +impl ForeignFrom<user_api::AuthConfig> for common_enums::UserAuthType { + fn foreign_from(from: user_api::AuthConfig) -> Self { + match from { + user_api::AuthConfig::OpenIdConnect { .. } => Self::OpenIdConnect, + user_api::AuthConfig::Password => Self::Password, + user_api::AuthConfig::MagicLink => Self::MagicLink, + } + } +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 51f762e3713..3a7cb3ba2a0 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -420,6 +420,12 @@ pub enum Flow { TerminateTwoFactorAuth, // Check 2FA status TwoFactorAuthStatus, + // Create user authentication method + CreateUserAuthenticationMethod, + // Update user authentication method + UpdateUserAuthenticationMethod, + // List user authentication methods + ListUserAuthenticationMethods, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index 0ada6513ff0..3434bcb67dd 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -58,6 +58,8 @@ pub struct MockDb { pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>, pub roles: Arc<Mutex<Vec<store::role::Role>>>, pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>, + pub user_authentication_methods: + Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>, } impl MockDb { @@ -102,6 +104,7 @@ impl MockDb { authentications: Default::default(), roles: Default::default(), user_key_store: Default::default(), + user_authentication_methods: Default::default(), }) } } diff --git a/migrations/2024-06-10-084722_create_user_authentication_methods_table/down.sql b/migrations/2024-06-10-084722_create_user_authentication_methods_table/down.sql new file mode 100644 index 00000000000..e12da6d51ab --- /dev/null +++ b/migrations/2024-06-10-084722_create_user_authentication_methods_table/down.sql @@ -0,0 +1,4 @@ +-- This file should undo anything in `up.sql` +DROP INDEX IF EXISTS auth_id_index; +DROP INDEX IF EXISTS owner_id_index; +DROP TABLE IF EXISTS user_authentication_methods; diff --git a/migrations/2024-06-10-084722_create_user_authentication_methods_table/up.sql b/migrations/2024-06-10-084722_create_user_authentication_methods_table/up.sql new file mode 100644 index 00000000000..4bdb835eeb1 --- /dev/null +++ b/migrations/2024-06-10-084722_create_user_authentication_methods_table/up.sql @@ -0,0 +1,16 @@ +-- Your SQL goes here +CREATE TABLE IF NOT EXISTS user_authentication_methods ( + id VARCHAR(64) PRIMARY KEY, + auth_id VARCHAR(64) NOT NULL, + owner_id VARCHAR(64) NOT NULL, + owner_type VARCHAR(64) NOT NULL, + auth_type VARCHAR(64) NOT NULL, + private_config bytea, + public_config JSONB, + allow_signup BOOLEAN NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + last_modified_at TIMESTAMP NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS auth_id_index ON user_authentication_methods (auth_id); +CREATE INDEX IF NOT EXISTS owner_id_index ON user_authentication_methods (owner_id);
2024-06-13T12:10:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The PR: - Sets up schema for user authentication methods - adds queries to interact with schema - adds endpoints to create, update and list authentication methods ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> 1. `config/config.example.toml` 2. `config/deployments/env_specific.toml` 3. `config/development.toml` 4. `config/docker_compose.toml` ## Motivation and Context Closes [#4998](https://github.com/juspay/hyperswitch/issues/4998) ## How did you test it? To create authentication method, ( auth is admin_api_key only): ``` curl --location 'http://localhost:8080/user/auth' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --header 'Cookie: Cookie_1=value' \ --data ' { "owner_id": "pw", "owner_type": "tenant", "auth_method": { "auth_type": "open_id_connect", "private_config": { "base_url": "hello.com", "client_id": "something", "client_secret": "something", "private_key": "something" }, "public_config": { "name": "okta" } }, "allow_signup": true }' ``` Response: 200 OK if auth method got created successfully. To update ``` curl --location --request PUT 'http://localhost:8080/user/auth' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --header 'Cookie: Cookie_1=value' \ --data '{ "id": "65ff02eb-f3dc-4afc-b8ac-cef2a30c4d12", "auth_method": { "auth_type": "open_id_connect", "private_config": { "base_url": "hello.com", "client_id": "something", "client_secret": "something_update", "private_key": "something_update" }, "public_config": { "name": "okta" } } } ' ``` Response will be 200 OK for success full auth config update To get list of authentication methods ``` curl --location 'http://localhost:8080/user/auth/list?auth_id=cbd4e678-6c09-4211-8611-74700aa1f695' \ --header 'Cookie: Cookie_1=value' \ --data '' ``` Response ``` [ { "id": "6b543648-4d47-498d-bcc2-68132dbf8521", "auth_id": "cbd4e678-6c09-4211-8611-74700aa1f695", "auth_method": { "type": "open_id_connect", "name": "okta" }, "allow_signup": true }, { "id": "1364c40d-1c5a-4dc9-ae28-ce908f537e83", "auth_id": "cbd4e678-6c09-4211-8611-74700aa1f695", "auth_method": { "type": "password", "name": null }, "allow_signup": true } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f84ed6a8a00cd5f28debfbc1bb1f8dba14eaa387
juspay/hyperswitch
juspay__hyperswitch-4986
Bug: feat(events): forward the tenant configuration as part of the kafka message In a previous [issue](https://github.com/juspay/hyperswitch/issues/4595) we've added tenant id to kafka events so that it can be used in downstream clickhouse, But due to recent changes the tenant_id won't be used as a unique identifier on clickhouse and instead we need to pass in the entire `Tenant` object to kafka store, with this the underlying `KafkaProducer` will accept a `Tenant` as well and send the clickhouse_database property from it as a field.
diff --git a/config/config.example.toml b/config/config.example.toml index aa98c0533e3..83c05c90119 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -698,7 +698,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 1cf8699f695..a7bd116a322 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -293,7 +293,7 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } diff --git a/config/development.toml b/config/development.toml index 49bc7756cc0..fb09efc74d7 100644 --- a/config/development.toml +++ b/config/development.toml @@ -696,7 +696,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 7f89acd01e2..42256f47121 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -524,7 +524,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 34dcc35d9ee..67fc43875a6 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -854,7 +854,7 @@ impl AnalyticsProvider { pub async fn from_conf( config: &AnalyticsConfig, - tenant: &dyn storage_impl::config::ClickHouseConfig, + tenant: &dyn storage_impl::config::TenantConfig, ) -> Self { match config { AnalyticsConfig::Sqlx { sqlx } => { diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index 9ed03c6d2ce..ec43259ad2f 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -43,14 +43,12 @@ where let start_instant = Instant::now(); logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); - let req_state = state.get_req_state(); let server_wrap_util_res = metrics::request::record_request_time_metric( api::server_wrap_util( &flow, state.clone().into(), request.headers(), - req_state, request, payload, func, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index adab685ea09..1b8ca2b148d 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -176,9 +176,6 @@ impl storage_impl::config::TenantConfig for Tenant { fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } -} - -impl storage_impl::config::ClickHouseConfig for Tenant { fn get_clickhouse_database(&self) -> &str { self.clickhouse_database.as_str() } @@ -188,6 +185,7 @@ impl storage_impl::config::ClickHouseConfig for Tenant { pub struct GlobalTenant { pub schema: String, pub redis_key_prefix: String, + pub clickhouse_database: String, } impl storage_impl::config::TenantConfig for GlobalTenant { @@ -197,6 +195,9 @@ impl storage_impl::config::TenantConfig for GlobalTenant { fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } + fn get_clickhouse_database(&self) -> &str { + self.clickhouse_database.as_str() + } } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index b9d2f0907a2..5f44b941fd2 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -26,7 +26,7 @@ use scheduler::{ SchedulerInterface, }; use serde::Serialize; -use storage_impl::redis::kv_store::RedisConnInterface; +use storage_impl::{config::TenantConfig, redis::kv_store::RedisConnInterface}; use time::PrimitiveDateTime; use super::{ @@ -89,7 +89,13 @@ pub struct KafkaStore { } impl KafkaStore { - pub async fn new(store: Store, kafka_producer: KafkaProducer, tenant_id: TenantID) -> Self { + pub async fn new( + store: Store, + mut kafka_producer: KafkaProducer, + tenant_id: TenantID, + tenant_config: &dyn TenantConfig, + ) -> Self { + kafka_producer.set_tenancy(tenant_config); Self { kafka_producer, diesel_store: store, diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index b7ab4ebaa1e..e9a1a17638c 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -6,7 +6,7 @@ use hyperswitch_domain_models::errors::{StorageError, StorageResult}; use masking::ErasedMaskSerialize; use router_env::logger; use serde::{Deserialize, Serialize}; -use storage_impl::errors::ApplicationError; +use storage_impl::{config::TenantConfig, errors::ApplicationError}; use time::PrimitiveDateTime; use crate::{ @@ -90,6 +90,11 @@ impl EventsHandler { Self::Logs(logger) => logger.log_event(event), }; } + pub fn add_tenant(&mut self, tenant_config: &dyn TenantConfig) { + if let Self::Kafka(kafka_producer) = self { + kafka_producer.set_tenancy(tenant_config); + } + } } impl MessagingInterface for EventsHandler { diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 4f79670cac0..94f5511ab79 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -344,6 +344,7 @@ impl AppState { .expect("Failed to create store"), kafka_client.clone(), TenantID(tenant.get_schema().to_string()), + tenant, ) .await, ), @@ -377,22 +378,19 @@ impl AppState { .await } - pub fn get_req_state(&self) -> ReqState { - ReqState { - event_context: events::EventContext::new(self.event_handler.clone()), - } - } pub fn get_session_state<E, F>(self: Arc<Self>, tenant: &str, err: F) -> Result<SessionState, E> where F: FnOnce() -> E + Copy, { let tenant_conf = self.conf.multitenancy.get_tenant(tenant).ok_or_else(err)?; + let mut event_handler = self.event_handler.clone(); + event_handler.add_tenant(tenant_conf); Ok(SessionState { store: self.stores.get(tenant).ok_or_else(err)?.clone(), global_store: self.global_store.clone(), conf: Arc::clone(&self.conf), api_client: self.api_client.clone(), - event_handler: self.event_handler.clone(), + event_handler, #[cfg(feature = "olap")] pool: self.pools.get(tenant).ok_or_else(err)?.clone(), file_storage_client: self.file_storage_client.clone(), diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index ea9ce177439..cba859c07c8 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -751,22 +751,13 @@ pub enum AuthFlow { #[allow(clippy::too_many_arguments)] #[instrument( - skip( - request, - payload, - state, - func, - api_auth, - request_state, - incoming_request_header - ), + skip(request, payload, state, func, api_auth, incoming_request_header), fields(merchant_id) )] pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>( flow: &'a impl router_env::types::FlowMetric, state: web::Data<AppState>, incoming_request_header: &HeaderMap, - mut request_state: ReqState, request: &'a HttpRequest, payload: T, func: F, @@ -788,12 +779,6 @@ where .attach_printable("Unable to extract request id from request") .change_context(errors::ApiErrorResponse::InternalServerError.switch())?; - request_state.event_context.record_info(request_id); - request_state - .event_context - .record_info(("flow".to_string(), flow.to_string())); - // request_state.event_context.record_info(request.clone()); - let mut app_state = state.get_ref().clone(); let start_instant = Instant::now(); @@ -826,9 +811,6 @@ where } })?? }; - request_state - .event_context - .record_info(("tenant_id".to_string(), tenant_id.to_string())); // let tenant_id = "public".to_string(); let mut session_state = Arc::new(app_state.clone()).get_session_state(tenant_id.as_str(), || { @@ -838,6 +820,16 @@ where .switch() })?; session_state.add_request_id(request_id); + let mut request_state = session_state.get_req_state(); + + request_state.event_context.record_info(request_id); + request_state + .event_context + .record_info(("flow".to_string(), flow.to_string())); + + request_state + .event_context + .record_info(("tenant_id".to_string(), tenant_id.to_string())); // Currently auth failures are not recorded as API events let (auth_out, auth_type) = api_auth @@ -965,7 +957,6 @@ where ApplicationResponse<Q>: Debug, E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context, { - let req_state = state.get_req_state(); let request_method = request.method().as_str(); let url_path = request.path(); @@ -1000,7 +991,6 @@ where &flow, state.clone(), incoming_request_header, - req_state, request, payload, func, diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index baa78339d91..78e08c1c60b 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -9,6 +9,8 @@ use rdkafka::{ message::{Header, OwnedHeaders}, producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer}, }; +use serde_json::Value; +use storage_impl::config::TenantConfig; #[cfg(feature = "payouts")] pub mod payout; use diesel_models::fraud_check::FraudCheck; @@ -70,21 +72,24 @@ struct KafkaEvent<'a, T: KafkaMessage> { event: &'a T, sign_flag: i32, tenant_id: TenantID, + clickhouse_database: Option<String>, } impl<'a, T: KafkaMessage> KafkaEvent<'a, T> { - fn new(event: &'a T, tenant_id: TenantID) -> Self { + fn new(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self { Self { event, sign_flag: 1, tenant_id, + clickhouse_database, } } - fn old(event: &'a T, tenant_id: TenantID) -> Self { + fn old(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self { Self { event, sign_flag: -1, tenant_id, + clickhouse_database, } } } @@ -263,6 +268,7 @@ pub struct KafkaProducer { payout_analytics_topic: String, consolidated_events_topic: String, authentication_analytics_topic: String, + ckh_database_name: Option<String>, } struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); @@ -285,6 +291,10 @@ pub enum KafkaError { #[allow(unused)] impl KafkaProducer { + pub fn set_tenancy(&mut self, tenant_config: &dyn TenantConfig) { + self.ckh_database_name = Some(tenant_config.get_clickhouse_database().to_string()); + } + pub async fn create(conf: &KafkaSettings) -> MQResult<Self> { Ok(Self { producer: Arc::new(RdKafkaProducer( @@ -307,6 +317,7 @@ impl KafkaProducer { payout_analytics_topic: conf.payout_analytics_topic.clone(), consolidated_events_topic: conf.consolidated_events_topic.clone(), authentication_analytics_topic: conf.authentication_analytics_topic.clone(), + ckh_database_name: None, }) } @@ -342,6 +353,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaFraudCheck::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative fraud check event {negative_event:?}") @@ -351,6 +363,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaFraudCheck::from_storage(attempt), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add positive fraud check event {attempt:?}") @@ -375,6 +388,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaPaymentAttempt::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative attempt event {negative_event:?}") @@ -384,6 +398,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaPaymentAttempt::from_storage(attempt), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))?; @@ -402,6 +417,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaPaymentAttempt::from_storage(delete_old_attempt), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative attempt event {delete_old_attempt:?}") @@ -418,6 +434,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaAuthentication::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative authentication event {negative_event:?}") @@ -427,6 +444,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaAuthentication::from_storage(authentication), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add positive authentication event {authentication:?}") @@ -451,6 +469,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaPaymentIntent::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative intent event {negative_event:?}") @@ -460,6 +479,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaPaymentIntent::from_storage(intent), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))?; @@ -478,6 +498,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaPaymentIntent::from_storage(delete_old_intent), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative intent event {delete_old_intent:?}") @@ -494,6 +515,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaRefund::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative refund event {negative_event:?}") @@ -503,6 +525,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaRefund::from_storage(refund), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?; @@ -521,6 +544,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaRefund::from_storage(delete_old_refund), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative refund event {delete_old_refund:?}") @@ -537,6 +561,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaDispute::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative dispute event {negative_event:?}") @@ -546,6 +571,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaDispute::from_storage(dispute), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))?; @@ -564,13 +590,21 @@ impl KafkaProducer { tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_payout { - self.log_event(&KafkaEvent::old(&negative_event, tenant_id.clone())) - .attach_printable_lazy(|| { - format!("Failed to add negative payout event {negative_event:?}") - })?; + self.log_event(&KafkaEvent::old( + &negative_event, + tenant_id.clone(), + self.ckh_database_name.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add negative payout event {negative_event:?}") + })?; }; - self.log_event(&KafkaEvent::new(payout, tenant_id.clone())) - .attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}")) + self.log_event(&KafkaEvent::new( + payout, + tenant_id.clone(), + self.ckh_database_name.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}")) } #[cfg(feature = "payouts")] @@ -579,10 +613,14 @@ impl KafkaProducer { delete_old_payout: &KafkaPayout<'_>, tenant_id: TenantID, ) -> MQResult<()> { - self.log_event(&KafkaEvent::old(delete_old_payout, tenant_id.clone())) - .attach_printable_lazy(|| { - format!("Failed to add negative payout event {delete_old_payout:?}") - }) + self.log_event(&KafkaEvent::old( + delete_old_payout, + tenant_id.clone(), + self.ckh_database_name.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add negative payout event {delete_old_payout:?}") + }) } pub fn get_topic(&self, event: EventType) -> &str { @@ -631,7 +669,14 @@ impl MessagingInterface for KafkaProducer { let topic = self.get_topic(data.get_message_class()); let json_data = data .masked_serialize() - .and_then(|i| serde_json::to_vec(&i)) + .and_then(|mut value| { + if let Value::Object(ref mut map) = value { + if let Some(db_name) = self.ckh_database_name.clone() { + map.insert("clickhouse_database".to_string(), Value::String(db_name)); + } + } + serde_json::to_vec(&value) + }) .change_context(EventsError::SerializationError)?; let mut headers = OwnedHeaders::new(); for (k, v) in metadata.iter() { @@ -640,6 +685,10 @@ impl MessagingInterface for KafkaProducer { value: Some(v), }); } + headers = headers.insert(Header { + key: "clickhouse_database", + value: self.ckh_database_name.as_ref(), + }); self.producer .0 .send( diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs index bb006b6a9e5..ac68d1718a9 100644 --- a/crates/storage_impl/src/config.rs +++ b/crates/storage_impl/src/config.rs @@ -36,9 +36,6 @@ impl DbConnectionParams for Database { pub trait TenantConfig: Send + Sync { fn get_schema(&self) -> &str; fn get_redis_key_prefix(&self) -> &str; -} - -pub trait ClickHouseConfig: TenantConfig + Send + Sync { fn get_clickhouse_database(&self) -> &str; }
2024-07-05T12:28:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Enhance the KafkaProducer struct to include a clickhouse_db_name field. This field is needed for generating audit events that do not use KafkaStore. Additionally, we will implement a method to add tenant details within KafkaProducer and propagate this functionality through EventsHandler. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 is to support multitenancy. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> After making a payment, you can observe a new field added at the end: `clickhouse_database = default` for `[Topics] hyperswitch-payment-attempt-events` for sandbox the `clickhouse_database` should have the `hyperswitch_sandbox` or the current clickhouse db in use. <img width="949" alt="image" src="https://github.com/juspay/hyperswitch/assets/89402434/417e6de2-4d68-4616-85f6-7d6114bd3177"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
876eeea0f426f63d0419021ba85372a016d46e27
juspay/hyperswitch
juspay__hyperswitch-4970
Bug: bug(user): Magic link is not expiring after being used once When a verified user is using magic link, that magic link is not blacklisted after being used once. User is able to use the same magic link to login to dashboard multiple times.
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c78f2c8080f..7e79e9e2e89 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -505,10 +505,8 @@ pub async fn reset_password_token_only_flow( let user = state .global_store - .update_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, + .update_user_by_user_id( + user_from_db.get_user_id(), storage_user::UserUpdate::PasswordUpdate { password: hash_password, }, @@ -516,6 +514,17 @@ pub async fn reset_password_token_only_flow( .await .change_context(UserErrors::InternalServerError)?; + if !user_from_db.is_verified() { + let _ = state + .global_store + .update_user_by_user_id( + user_from_db.get_user_id(), + storage_user::UserUpdate::VerifyUser, + ) + .await + .map_err(|e| logger::error!(?e)); + } + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) .await .map_err(|e| logger::error!(?e)); @@ -1021,6 +1030,17 @@ pub async fn accept_invite_from_email_token_only_flow( .await .change_context(UserErrors::InternalServerError)?; + if !user_from_db.is_verified() { + let _ = state + .global_store + .update_user_by_user_id( + user_from_db.get_user_id(), + storage_user::UserUpdate::VerifyUser, + ) + .await + .map_err(|e| logger::error!(?e)); + } + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) .await .map_err(|e| logger::error!(?e)); @@ -1476,13 +1496,9 @@ pub async fn verify_email_token_only_flow( .change_context(UserErrors::InternalServerError)? .into(); - if matches!(user_token.origin, domain::Origin::VerifyEmail) - || matches!(user_token.origin, domain::Origin::MagicLink) - { - let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) - .await - .map_err(|e| logger::error!(?e)); - } + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::VerifyEmail.into())?; diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 47f26ce04e5..5ff79b7feee 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -837,6 +837,10 @@ impl UserFromStorage { Ok(Some(days_left_for_verification.whole_days())) } + pub fn is_verified(&self) -> bool { + self.0.is_verified + } + pub fn is_password_rotate_required(&self, state: &SessionState) -> UserResult<bool> { let last_password_modified_at = if let Some(last_password_modified_at) = self.0.last_password_modified_at { diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 41ae12350fb..2ee9b389788 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -42,7 +42,7 @@ impl SPTFlow { Self::TOTP => Ok(true), // Main email APIs Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true), - Self::VerifyEmail => Ok(!user.0.is_verified), + Self::VerifyEmail => Ok(true), // Final Checks Self::ForceSetPassword => user.is_password_rotate_required(state), Self::MerchantSelect => user @@ -154,17 +154,15 @@ const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [ UserFlow::JWTFlow(JWTFlow::UserInfo), ]; -const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 5] = [ +const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 4] = [ UserFlow::SPTFlow(SPTFlow::TOTP), - UserFlow::SPTFlow(SPTFlow::VerifyEmail), UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; -const RESET_PASSWORD_FLOW: [UserFlow; 3] = [ +const RESET_PASSWORD_FLOW: [UserFlow; 2] = [ UserFlow::SPTFlow(SPTFlow::TOTP), - UserFlow::SPTFlow(SPTFlow::VerifyEmail), UserFlow::SPTFlow(SPTFlow::ResetPassword), ];
2024-06-12T12:43:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently verify email API will be picked by the decision manager only if the user is not verified. But this API should be called always in case of verify email and magic link flow. This PR fixes it. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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 #4970. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user email" }' ``` You will receive a magic link to the email provided. Once the link in the email is used to login to dashboard, the link should not work anymore. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
4651584ecc25e40a285b3544315901145d8c6b4b
juspay/hyperswitch
juspay__hyperswitch-4957
Bug: [BUG] Fix typo in `integration_test.toml` `krungsri_bank` it is.
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 738edcbda84..5abbc870fd0 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -9,7 +9,7 @@ online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,pla 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,krungsrgiri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" +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" @@ -143,8 +143,8 @@ bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" # Mandate suppor bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # Mandate supported payment method type and connector for bank_redirect [mandates.update_mandate_supported] -card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card -card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] connector_list = "stripe,adyen,cybersource"
2024-06-12T05:27:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR reverts typo introduced in https://github.com/juspay/hyperswitch/pull/4398 in `integration_test.toml` that resulted in deployments to fail. Resolves #4957 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> config/deployments/integration_test.toml ## 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). --> NIL ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Deployments should succeed. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
5a81b50ae20760ce3c281719e0853c0f60f23734
juspay/hyperswitch
juspay__hyperswitch-4950
Bug: [FEATURE] [BOA/CYB] Make all BillTo fields optional ### Feature Description Make all BillTo fields optional for prod testing ### Possible Implementation Make all BillTo fields optional for prod testing ### 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 671cc40e05c..143c1a4c6fa 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -260,15 +260,15 @@ pub struct Amount { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { - first_name: Secret<String>, - last_name: Secret<String>, - address1: Secret<String>, - locality: Secret<String>, + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address1: Option<Secret<String>>, + locality: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] administrative_area: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] postal_code: Option<Secret<String>>, - country: api_enums::CountryAlpha2, + country: Option<api_enums::CountryAlpha2>, email: pii::Email, } @@ -442,47 +442,77 @@ impl<F, T> } // for bankofamerica each item in Billing is mandatory +// fn build_bill_to( +// address_details: &payments::Address, +// email: pii::Email, +// ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { +// let address = address_details +// .address +// .as_ref() +// .ok_or_else(utils::missing_field_err("billing.address"))?; + +// let country = address.get_country()?.to_owned(); +// let first_name = address.get_first_name()?; + +// let (administrative_area, postal_code) = +// if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { +// let mut state = address.to_state_code()?.peek().clone(); +// state.truncate(20); +// ( +// Some(Secret::from(state)), +// Some(address.get_zip()?.to_owned()), +// ) +// } else { +// let zip = address.zip.clone(); +// let mut_state = address.state.clone().map(|state| state.expose()); +// match mut_state { +// Some(mut state) => { +// state.truncate(20); +// (Some(Secret::from(state)), zip) +// } +// None => (None, zip), +// } +// }; +// Ok(BillTo { +// first_name: first_name.clone(), +// last_name: address.get_last_name().unwrap_or(first_name).clone(), +// address1: address.get_line1()?.to_owned(), +// locality: Secret::new(address.get_city()?.to_owned()), +// administrative_area, +// postal_code, +// country, +// email, +// }) +// } + fn build_bill_to( - address_details: &payments::Address, + address_details: Option<&payments::Address>, email: pii::Email, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { - let address = address_details - .address - .as_ref() - .ok_or_else(utils::missing_field_err("billing.address"))?; - - let country = address.get_country()?.to_owned(); - let first_name = address.get_first_name()?; - - let (administrative_area, postal_code) = - if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { - let mut state = address.to_state_code()?.peek().clone(); - state.truncate(20); - ( - Some(Secret::from(state)), - Some(address.get_zip()?.to_owned()), - ) - } else { - let zip = address.zip.clone(); - let mut_state = address.state.clone().map(|state| state.expose()); - match mut_state { - Some(mut state) => { - state.truncate(20); - (Some(Secret::from(state)), zip) - } - None => (None, zip), - } - }; - Ok(BillTo { - first_name: first_name.clone(), - last_name: address.get_last_name().unwrap_or(first_name).clone(), - address1: address.get_line1()?.to_owned(), - locality: Secret::new(address.get_city()?.to_owned()), - administrative_area, - postal_code, - country, - email, - }) + let default_address = BillTo { + first_name: None, + last_name: None, + address1: None, + locality: None, + administrative_area: None, + postal_code: None, + country: None, + email: email.clone(), + }; + Ok(address_details + .and_then(|addr| { + addr.address.as_ref().map(|addr| BillTo { + first_name: addr.first_name.clone(), + last_name: addr.last_name.clone(), + address1: addr.line1.clone(), + locality: addr.city.clone(), + administrative_area: addr.to_state_code_as_optional().ok().flatten(), + postal_code: addr.zip.clone(), + country: addr.country, + email, + }) + }) + .unwrap_or(default_address)) } impl From<CardIssuer> for String { @@ -876,7 +906,7 @@ impl ), ) -> 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 bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); let payment_information = PaymentInformation::try_from(&ccard)?; @@ -939,7 +969,7 @@ impl ), ) -> 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 bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::try_from(&ccard)?; let processing_information = ProcessingInformation::try_from((item, None, None))?; @@ -976,7 +1006,7 @@ impl ), ) -> 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 bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, @@ -1030,7 +1060,7 @@ impl ), ) -> 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 bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::from(&google_pay_data); let processing_information = @@ -1081,8 +1111,10 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> }, None => { let email = item.router_data.request.get_email()?; - let bill_to = - build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to( + item.router_data.get_optional_billing(), + email, + )?; let order_information: OrderInformationWithBill = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = @@ -1897,7 +1929,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsPreProcessingRouterData>> .1 .to_string(); let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details, bill_to: Some(bill_to), @@ -3098,7 +3130,7 @@ impl TryFrom<&types::SetupMandateRouterData> for OrderInformationWithBill { fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { let email = item.request.get_email()?; - let bill_to = build_bill_to(item.get_billing()?, email)?; + let bill_to = build_bill_to(item.get_optional_billing(), email)?; Ok(Self { amount_details: Amount { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index edc5c0cac1d..346f66b5d2e 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -65,7 +65,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { let email = item.request.get_email()?; - let bill_to = build_bill_to(item.get_billing()?, email)?; + let bill_to = build_bill_to(item.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details: Amount { @@ -478,15 +478,15 @@ impl From<PaymentSolution> for String { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { - first_name: Secret<String>, - last_name: Secret<String>, - address1: Secret<String>, - locality: String, + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address1: Option<Secret<String>>, + locality: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] administrative_area: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] postal_code: Option<Secret<String>>, - country: api_enums::CountryAlpha2, + country: Option<api_enums::CountryAlpha2>, email: pii::Email, } @@ -862,47 +862,77 @@ impl } // for cybersource each item in Billing is mandatory +// fn build_bill_to( +// address_details: &payments::Address, +// email: pii::Email, +// ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { +// let address = address_details +// .address +// .as_ref() +// .ok_or_else(utils::missing_field_err("billing.address"))?; + +// let country = address.get_country()?.to_owned(); +// let first_name = address.get_first_name()?; + +// let (administrative_area, postal_code) = +// if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { +// let mut state = address.to_state_code()?.peek().clone(); +// state.truncate(20); +// ( +// Some(Secret::from(state)), +// Some(address.get_zip()?.to_owned()), +// ) +// } else { +// let zip = address.zip.clone(); +// let mut_state = address.state.clone().map(|state| state.expose()); +// match mut_state { +// Some(mut state) => { +// state.truncate(20); +// (Some(Secret::from(state)), zip) +// } +// None => (None, zip), +// } +// }; +// Ok(BillTo { +// first_name: first_name.clone(), +// last_name: address.get_last_name().unwrap_or(first_name).clone(), +// address1: address.get_line1()?.to_owned(), +// locality: address.get_city()?.to_owned(), +// administrative_area, +// postal_code, +// country, +// email, +// }) +// } + fn build_bill_to( - address_details: &payments::Address, + address_details: Option<&payments::Address>, email: pii::Email, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { - let address = address_details - .address - .as_ref() - .ok_or_else(utils::missing_field_err("billing.address"))?; - - let country = address.get_country()?.to_owned(); - let first_name = address.get_first_name()?; - - let (administrative_area, postal_code) = - if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { - let mut state = address.to_state_code()?.peek().clone(); - state.truncate(20); - ( - Some(Secret::from(state)), - Some(address.get_zip()?.to_owned()), - ) - } else { - let zip = address.zip.clone(); - let mut_state = address.state.clone().map(|state| state.expose()); - match mut_state { - Some(mut state) => { - state.truncate(20); - (Some(Secret::from(state)), zip) - } - None => (None, zip), - } - }; - Ok(BillTo { - first_name: first_name.clone(), - last_name: address.get_last_name().unwrap_or(first_name).clone(), - address1: address.get_line1()?.to_owned(), - locality: address.get_city()?.to_owned(), - administrative_area, - postal_code, - country, - email, - }) + let default_address = BillTo { + first_name: None, + last_name: None, + address1: None, + locality: None, + administrative_area: None, + postal_code: None, + country: None, + email: email.clone(), + }; + Ok(address_details + .and_then(|addr| { + addr.address.as_ref().map(|addr| BillTo { + first_name: addr.first_name.clone(), + last_name: addr.last_name.clone(), + address1: addr.line1.clone(), + locality: addr.city.clone(), + administrative_area: addr.to_state_code_as_optional().ok().flatten(), + postal_code: addr.zip.clone(), + country: addr.country, + email, + }) + }) + .unwrap_or(default_address)) } impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { @@ -937,7 +967,7 @@ impl ), ) -> 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 bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let card_issuer = ccard.get_card_issuer(); @@ -1015,7 +1045,7 @@ impl ), ) -> 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 bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); let card_issuer = ccard.get_card_issuer(); @@ -1096,7 +1126,7 @@ impl ), ) -> 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 bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, @@ -1163,7 +1193,7 @@ impl ), ) -> 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 bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = @@ -1223,8 +1253,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> }, None => { let email = item.router_data.request.get_email()?; - let bill_to = - build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to( + item.router_data.get_optional_billing(), + email, + )?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = @@ -2212,7 +2244,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> .1 .to_string(); let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details, bill_to: Some(bill_to),
2024-06-11T11:59:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Make billTo fields optional in connector BOA and Cybersource. This change is required for prod testing. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## 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/4950 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Testing should be done for BOA and Cybersource. Payments should work if billing address is passed and payments should be failed at connector if billing address is not passed. Failure Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mF5ApaF7qylFyewcvRbsOVw9bhOUy2ufhC8MutbWQvLwNWWqX7CZGDPf5SnZ6KRE' \ --data-raw '{ "amount": 101, "currency": "USD", "confirm": true, "customer_id": "mearX", "email": "guest@deepanshu.com", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "card_cvc": "123" } } }' ``` Failure Response: ``` { "payment_id": "pay_7iL2BAQtdP07gisZ5lgy", "merchant_id": "merchant_1718024306", "status": "failed", "amount": 101, "net_amount": 101, "amount_capturable": 0, "amount_received": null, "connector": "bankofamerica", "client_secret": "pay_7iL2BAQtdP07gisZ5lgy_secret_aLewy2zRmIcXiVmgPRsZ", "created": "2024-06-11T12:11:53.042Z", "currency": "USD", "customer_id": "mearX", "customer": { "id": "mearX", "name": "John Doe", "email": "guest@deepanshu.com", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "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_extended_bin": null, "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_hlcvyB0Vp6vQJ2v4Uk5g", "shipping": null, "billing": null, "order_details": null, "email": "guest@deepanshu.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": "MISSING_FIELD", "error_message": "Declined - The request is missing one or more fields, detailed_error_information: orderInformation.billTo.locality : MISSING_FIELD, orderInformation.billTo.address1 : MISSING_FIELD, orderInformation.billTo.country : MISSING_FIELD", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "mearX", "created_at": 1718107912, "expires": 1718111512, "secret": "epk_8c55074dbcc94632811fe1bd02a06edb" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_sjoiFN7MPB9SdG5Zr0iT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_QxbSnL7xEEr3Wc2sODHD", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-11T12:26:53.041Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-11T12:11:54.679Z", "charges": null, "frm_metadata": null } ``` Success Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mF5ApaF7qylFyewcvRbsOVw9bhOUy2ufhC8MutbWQvLwNWWqX7CZGDPf5SnZ6KRE' \ --data-raw '{ "amount": 101, "currency": "USD", "confirm": true, "customer_id": "mearX", "email": "guest@deepanshu.com", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "card_cvc": "123" } }, "billing": { "address": { "line1": "eqnkl", "city": "San Francisco", "state": "BC", "zip": "V2S 1A6", "country": "DE", "first_name": "John", "last_name": "Bond" } } }' ``` Success Response: ``` { "payment_id": "pay_kRyRpMuXP8jqDMCkwWcI", "merchant_id": "merchant_1718024306", "status": "succeeded", "amount": 101, "net_amount": 101, "amount_capturable": 0, "amount_received": 101, "connector": "bankofamerica", "client_secret": "pay_kRyRpMuXP8jqDMCkwWcI_secret_kC4PSvgrobptzODtJgEn", "created": "2024-06-11T12:12:55.139Z", "currency": "USD", "customer_id": "mearX", "customer": { "id": "mearX", "name": "John Doe", "email": "guest@deepanshu.com", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "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_extended_bin": null, "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" }, "approval_code": "831000", "consumer_authentication_response": { "code": "2", "codeRaw": "2" }, "cavv": null, "eci": null, "eci_raw": null }, "authentication_data": { "retrieval_reference_number": "416312127150", "acs_transaction_id": null, "system_trace_audit_number": "127150" } }, "billing": null }, "payment_token": "token_JLkgC0o4OvAPM1lxzecO", "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "DE", "line1": "eqnkl", "line2": null, "line3": null, "zip": "V2S 1A6", "state": "BC", "first_name": "John", "last_name": "Bond" }, "phone": null, "email": null }, "order_details": null, "email": "guest@deepanshu.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": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "mearX", "created_at": 1718107975, "expires": 1718111575, "secret": "epk_b51ed8a854734e3c96a4c702ce610921" }, "manual_retry_allowed": false, "connector_transaction_id": "7181079753616046504951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_kRyRpMuXP8jqDMCkwWcI_1", "payment_link": null, "profile_id": "pro_sjoiFN7MPB9SdG5Zr0iT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_QxbSnL7xEEr3Wc2sODHD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-11T12:27:55.139Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-11T12:12:56.234Z", "charges": null, "frm_metadata": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b705757be37a9803b964ef94d04c664c0f1e102d