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-3468
Bug: feat: blacklist user Setup user blacklisting.
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 3f0febcc592..325ca980243 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -21,7 +21,7 @@ pub mod routes { routes::AppState, services::{ api, - authentication::{self as auth, AuthToken, AuthenticationData}, + authentication::{self as auth, AuthenticationData}, authorization::permissions::Permission, ApplicationResponse, }, @@ -378,23 +378,13 @@ pub mod routes { req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { - let state_ref = &state; - let req_headers = &req.headers(); - let flow = AnalyticsFlow::GenerateRefundReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), - |state, auth: AuthenticationData, payload| async move { - let jwt_payload = - auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await; - - let user_id = jwt_payload - .change_context(AnalyticsError::UnknownError)? - .user_id; - + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move { let user = UserInterface::find_user_by_id(&*state.store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; @@ -430,23 +420,13 @@ pub mod routes { req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { - let state_ref = &state; - let req_headers = &req.headers(); - let flow = AnalyticsFlow::GenerateDisputeReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), - |state, auth: AuthenticationData, payload| async move { - let jwt_payload = - auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await; - - let user_id = jwt_payload - .change_context(AnalyticsError::UnknownError)? - .user_id; - + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move { let user = UserInterface::find_user_by_id(&*state.store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; @@ -482,23 +462,13 @@ pub mod routes { req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { - let state_ref = &state; - let req_headers = &req.headers(); - let flow = AnalyticsFlow::GeneratePaymentReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), - |state, auth: AuthenticationData, payload| async move { - let jwt_payload = - auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await; - - let user_id = jwt_payload - .change_context(AnalyticsError::UnknownError)? - .user_id; - + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move { let user = UserInterface::find_user_by_id(&*state.store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 387da3c0641..12b688e3d3a 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -66,12 +66,16 @@ pub const ROUTING_CONFIG_ID_LENGTH: usize = 10; pub const LOCKER_REDIS_PREFIX: &str = "LOCKER_PM_TOKEN"; pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes -#[cfg(any(feature = "olap", feature = "oltp"))] pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days +pub const USER_BLACKLIST_PREFIX: &str = "BU_"; + #[cfg(feature = "email")] pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day +#[cfg(feature = "email")] +pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_"; + #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index ae66728e140..24b6eb9d127 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -264,6 +264,11 @@ pub async fn connect_account( } } +pub async fn signout(state: AppState, user_from_token: auth::UserFromToken) -> UserResponse<()> { + auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?; + Ok(ApplicationResponse::StatusOk) +} + pub async fn change_password( state: AppState, request: user_api::ChangePasswordRequest, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 4a726084c2c..a69220231f5 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -965,6 +965,7 @@ impl User { web::resource("/signin").route(web::post().to(user_signin_without_invite_checks)), ) .service(web::resource("/v2/signin").route(web::post().to(user_signin))) + .service(web::resource("/signout").route(web::post().to(signout))) .service(web::resource("/change_password").route(web::post().to(change_password))) .service(web::resource("/internal_signup").route(web::post().to(internal_user_signup))) .service(web::resource("/switch_merchant").route(web::post().to(switch_merchant_id))) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 4cd85efe8d5..a5362162dbc 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -164,6 +164,7 @@ impl From<Flow> for ApiIdentifier { | Flow::UserSignUp | Flow::UserSignInWithoutInviteChecks | Flow::UserSignIn + | Flow::Signout | Flow::ChangePassword | Flow::SetDashboardMetadata | Flow::GetMutltipleDashboardMetadata diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 88e19ddf755..48721afff59 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -116,6 +116,20 @@ pub async fn user_connect_account( .await } +pub async fn signout(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { + let flow = Flow::Signout; + Box::pin(api::server_wrap( + flow, + state.clone(), + &http_req, + (), + |state, user, _| user_core::signout(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn change_password( state: web::Data<AppState>, http_req: HttpRequest, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7f1e078ad53..221106612f3 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -36,6 +36,7 @@ use crate::{ types::domain, utils::OptionExt, }; +pub mod blacklist; #[derive(Clone, Debug)] pub struct AuthenticationData { @@ -333,6 +334,9 @@ where state: &A, ) -> RouterResult<(UserWithoutMerchantFromToken, AuthenticationType)> { let payload = parse_jwt_payload::<A, UserAuthToken>(request_headers, state).await?; + if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } Ok(( UserWithoutMerchantFromToken { @@ -495,6 +499,9 @@ where state: &A, ) -> RouterResult<((), AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } let permissions = authorization::get_permissions(&payload.role_id)?; authorization::check_authorization(&self.0, permissions)?; @@ -521,6 +528,9 @@ where state: &A, ) -> RouterResult<(UserFromToken, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } let permissions = authorization::get_permissions(&payload.role_id)?; authorization::check_authorization(&self.0, permissions)?; @@ -556,6 +566,9 @@ where state: &A, ) -> RouterResult<((), AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } let permissions = authorization::get_permissions(&payload.role_id)?; authorization::check_authorization(&self.required_permission, permissions)?; @@ -585,12 +598,6 @@ where Ok(payload) } -#[derive(serde::Deserialize)] -struct JwtAuthPayloadFetchMerchantAccount { - merchant_id: String, - role_id: String, -} - #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuth where @@ -601,9 +608,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { - let payload = - parse_jwt_payload::<A, JwtAuthPayloadFetchMerchantAccount>(request_headers, state) - .await?; + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } let permissions = authorization::get_permissions(&payload.role_id)?; authorization::check_authorization(&self.0, permissions)?; @@ -638,6 +646,56 @@ where } } +pub type AuthenticationDataWithUserId = (AuthenticationData, String); + +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationDataWithUserId, A> for JWTAuth +where + A: AppStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationDataWithUserId, AuthenticationType)> { + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + + let permissions = authorization::get_permissions(&payload.role_id)?; + authorization::check_authorization(&self.0, permissions)?; + + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + &payload.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::InvalidJwtToken) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store) + .await + .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; + + let auth = AuthenticationData { + merchant_account: merchant, + key_store, + }; + Ok(( + (auth.clone(), payload.user_id.clone()), + AuthenticationType::MerchantJwt { + merchant_id: auth.merchant_account.merchant_id.clone(), + user_id: None, + }, + )) + } +} + pub struct DashboardNoPermissionAuth; #[cfg(feature = "olap")] @@ -652,6 +710,9 @@ where state: &A, ) -> RouterResult<(UserFromToken, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } Ok(( UserFromToken { @@ -679,7 +740,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { - parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } Ok(((), AuthenticationType::NoAuth)) } diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs new file mode 100644 index 00000000000..6fab28433b4 --- /dev/null +++ b/crates/router/src/services/authentication/blacklist.rs @@ -0,0 +1,63 @@ +use std::sync::Arc; + +#[cfg(feature = "olap")] +use common_utils::date_time; +use error_stack::{IntoReport, ResultExt}; +use redis_interface::RedisConnectionPool; + +use crate::{ + consts::{JWT_TOKEN_TIME_IN_SECS, USER_BLACKLIST_PREFIX}, + core::errors::{ApiErrorResponse, RouterResult}, + routes::app::AppStateInfo, +}; +#[cfg(feature = "olap")] +use crate::{ + core::errors::{UserErrors, UserResult}, + routes::AppState, +}; + +#[cfg(feature = "olap")] +pub async fn insert_user_in_blacklist(state: &AppState, user_id: &str) -> UserResult<()> { + let user_blacklist_key = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); + let expiry = + expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; + let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + redis_conn + .set_key_with_expiry( + user_blacklist_key.as_str(), + date_time::now_unix_timestamp(), + expiry, + ) + .await + .change_context(UserErrors::InternalServerError) +} + +pub async fn check_user_in_blacklist<A: AppStateInfo>( + state: &A, + user_id: &str, + token_expiry: u64, +) -> RouterResult<bool> { + let token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); + let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; + let redis_conn = get_redis_connection(state)?; + redis_conn + .get_key::<Option<i64>>(token.as_str()) + .await + .change_context(ApiErrorResponse::InternalServerError) + .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) +} + +fn get_redis_connection<A: AppStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { + state + .store() + .get_redis_conn() + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection") +} + +fn expiry_to_i64(expiry: u64) -> RouterResult<i64> { + expiry + .try_into() + .into_report() + .change_context(ApiErrorResponse::InternalServerError) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ac2dfb47c63..c78455ffbe6 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -285,6 +285,8 @@ pub enum Flow { FrmFulfillment, /// Change password flow ChangePassword, + /// Signout flow + Signout, /// Set Dashboard Metadata flow SetDashboardMetadata, /// Get Multiple Dashboard Metadata flow
2024-01-29T10:37:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added blacklist for users. <!-- 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 Invalidate the token after logout. <!-- 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? Use the below api to logout. ``` curl --location --request POST '<URL>/user/signout' \ --header 'Authorization: Bearer JWT' ``` When you use the same token as above to test any other api then response will be `401`. <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d2accdef410319733d6174057bdca468bde1ae83
juspay/hyperswitch
juspay__hyperswitch-3464
Bug: [FEATURE] Add the configs for revoking as well as updating the mandates ### Feature Description Add envs of the connectors that support the revokinga s well as updation of mandates ### Possible Implementation Make an env that has the list of all the connectors that support revoke as well as mandate flow , and if we try to update or revoke the mandate for a connector that is not there in the list we throw a suitable error ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index dd1206b20dc..dda768bec3c 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -391,6 +391,9 @@ bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} # Mandate supp bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } +[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 # Required fields info used while listing the payment_method_data [required_fields.pay_later] # payment_method = "pay_later" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index dfb1fc9ee28..1ba455ee134 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -120,6 +120,10 @@ wallet.paypal.connector_list = "adyen" bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +[mandates.update_mandate_supported] +card.credit ={connector_list ="cybersource"} +card.debit = {connector_list ="cybersource"} + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 82d5c00c806..ae764682321 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -120,6 +120,10 @@ wallet.paypal.connector_list = "adyen" bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +[mandates.update_mandate_supported] +card.credit ={connector_list ="cybersource"} +card.debit = {connector_list ="cybersource"} + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index dfc3033ea20..1cac50298ff 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -120,6 +120,10 @@ wallet.paypal.connector_list = "adyen" bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +[mandates.update_mandate_supported] +card.credit ={connector_list ="cybersource"} +card.debit = {connector_list ="cybersource"} + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/development.toml b/config/development.toml index 1fd76d04ff5..1075452fbd6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -487,6 +487,10 @@ bank_debit.sepa = { connector_list = "gocardless"} bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +[mandates.update_mandate_supported] +card.credit ={connector_list ="cybersource"} +card.debit = {connector_list ="cybersource"} + [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 07a891efd34..a9d415230e9 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1011,6 +1011,23 @@ impl PaymentMethodData { self.to_owned() } } + pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { + match self { + Self::Card(_) => Some(api_enums::PaymentMethod::Card), + Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), + Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), + Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), + Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), + Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), + Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), + Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), + Self::Reward => Some(api_enums::PaymentMethod::Reward), + Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), + Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), + Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), + Self::CardToken(_) | Self::MandatePayment => None, + } + } } pub trait GetPaymentMethodType { diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index fc5ba0f55bc..71cd61ffa80 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -209,6 +209,7 @@ impl Default for Mandates { ])), ), ])), + update_mandate_supported: SupportedPaymentMethodsForMandate(HashMap::default()), } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 2519455f95a..2572d764d06 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -237,6 +237,7 @@ pub struct DummyConnector { #[derive(Debug, Deserialize, Clone)] pub struct Mandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, + pub update_mandate_supported: SupportedPaymentMethodsForMandate, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 7299ef624d8..e564e4a733e 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -59,7 +59,6 @@ pub async fn revoke_mandate( .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &req.mandate_id) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; - let mandate_revoke_status = match mandate.mandate_status { common_enums::MandateStatus::Active | common_enums::MandateStatus::Inactive diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index e9beb84c7bb..7b505e7c01c 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1219,6 +1219,7 @@ pub async fn list_payment_methods( mca.connector_name.clone(), pm_config_mapping, &state.conf.mandates.supported_payment_methods, + &state.conf.mandates.update_mandate_supported, ) .await?; } @@ -1985,6 +1986,7 @@ pub async fn filter_payment_methods( connector: String, config: &settings::ConnectorFilters, supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate, + supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { for payment_method in payment_methods.into_iter() { let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method); @@ -2091,13 +2093,20 @@ pub async fn filter_payment_methods( ), }; - if mandate_type_present || update_mandate_id_present { + if mandate_type_present { filter_pm_based_on_supported_payments_for_mandate( supported_payment_methods_for_mandate, &payment_method, &payment_method_object.payment_method_type, connector_variant, ) + } else if update_mandate_id_present { + filter_pm_based_on_update_mandate_support_for_connector( + supported_payment_methods_for_update_mandate, + &payment_method, + &payment_method_object.payment_method_type, + connector_variant, + ) } else { true } @@ -2121,6 +2130,19 @@ pub async fn filter_payment_methods( } Ok(()) } +pub fn filter_pm_based_on_update_mandate_support_for_connector( + supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate, + payment_method: &api_enums::PaymentMethod, + payment_method_type: &api_enums::PaymentMethodType, + connector: api_enums::Connector, +) -> bool { + supported_payment_methods_for_mandate + .0 + .get(payment_method) + .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type)) + .map(|supported_connectors| supported_connectors.connector_list.contains(&connector)) + .unwrap_or(false) +} fn filter_pm_based_on_supported_payments_for_mandate( supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate, 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 712184308dd..a81f97851d9 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -3,9 +3,11 @@ use error_stack::{IntoReport, ResultExt}; use super::{ConstructFlowSpecificData, Feature}; use crate::{ + configs::settings, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, + payment_methods::cards, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, }, @@ -60,106 +62,53 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup connector_request: Option<services::Request>, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { - let connector_integration: services::BoxedConnectorIntegration< - '_, - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - - let resp = services::execute_connector_processing_step( - state, - connector_integration, - &self, - call_connector_action.clone(), - connector_request, - ) - .await - .to_setup_mandate_failed_response()?; - - let is_mandate = resp.request.setup_mandate_details.is_some(); - - let pm_id = Box::pin(tokenization::save_payment_method( - state, - connector, - resp.to_owned(), - maybe_customer, - merchant_account, - self.request.payment_method_type, - key_store, - is_mandate, - )) - .await?; - if let Some(mandate_id) = self .request .setup_mandate_details .as_ref() .and_then(|mandate_data| mandate_data.update_mandate_id.clone()) { - let mandate = state - .store - .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &mandate_id) - .await - .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; - - let profile_id = mandate::helpers::get_profile_id_for_mandate( + self.update_mandate_flow( state, merchant_account, - mandate.clone(), + mandate_id, + connector, + key_store, + call_connector_action, + &state.conf.mandates.update_mandate_supported, + connector_request, + maybe_customer, ) - .await?; - match resp.response { - Ok(types::PaymentsResponseData::TransactionResponse { .. }) => { - let connector_integration: services::BoxedConnectorIntegration< - '_, - types::api::MandateRevoke, - types::MandateRevokeRequestData, - types::MandateRevokeResponseData, - > = connector.connector.get_connector_integration(); - let merchant_connector_account = helpers::get_merchant_connector_account( - state, - &merchant_account.merchant_id, - None, - key_store, - &profile_id, - &mandate.connector, - mandate.merchant_connector_id.as_ref(), - ) - .await?; - - let router_data = mandate::utils::construct_mandate_revoke_router_data( - merchant_connector_account, - merchant_account, - mandate.clone(), - ) - .await?; - - let _response = services::execute_connector_processing_step( - state, - connector_integration, - &router_data, - call_connector_action, - None, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - // TODO:Add the revoke mandate task to process tracker - mandate::update_mandate_procedure( - state, - resp, - mandate, - &merchant_account.merchant_id, - pm_id, - ) - .await - } - Ok(_) => Err(errors::ApiErrorResponse::InternalServerError) - .into_report() - .attach_printable("Unexpected response received")?, - Err(_) => Ok(resp), - } + .await } else { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::SetupMandate, + types::SetupMandateRequestData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &self, + call_connector_action.clone(), + connector_request, + ) + .await + .to_setup_mandate_failed_response()?; + let is_mandate = resp.request.setup_mandate_details.is_some(); + let pm_id = Box::pin(tokenization::save_payment_method( + state, + connector, + resp.to_owned(), + maybe_customer, + merchant_account, + self.request.payment_method_type, + key_store, + is_mandate, + )) + .await?; mandate::mandate_procedure( state, resp, @@ -310,6 +259,130 @@ impl types::SetupMandateRouterData { _ => Ok(self.clone()), } } + + async fn update_mandate_flow( + self, + state: &AppState, + merchant_account: &domain::MerchantAccount, + mandate_id: String, + connector: &api::ConnectorData, + key_store: &domain::MerchantKeyStore, + call_connector_action: payments::CallConnectorAction, + supported_connectors_for_update_mandate: &settings::SupportedPaymentMethodsForMandate, + connector_request: Option<services::Request>, + maybe_customer: &Option<domain::Customer>, + ) -> RouterResult<Self> { + let payment_method_type = self.request.payment_method_type; + + let payment_method = self.request.payment_method_data.get_payment_method(); + let supported_connectors_config = + payment_method + .zip(payment_method_type) + .map_or(false, |(pm, pmt)| { + cards::filter_pm_based_on_update_mandate_support_for_connector( + supported_connectors_for_update_mandate, + &pm, + &pmt, + connector.connector_name, + ) + }); + if supported_connectors_config { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::SetupMandate, + types::SetupMandateRequestData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &self, + call_connector_action.clone(), + connector_request, + ) + .await + .to_setup_mandate_failed_response()?; + let is_mandate = resp.request.setup_mandate_details.is_some(); + let pm_id = Box::pin(tokenization::save_payment_method( + state, + connector, + resp.to_owned(), + maybe_customer, + merchant_account, + self.request.payment_method_type, + key_store, + is_mandate, + )) + .await?; + let mandate = state + .store + .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &mandate_id) + .await + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + + let profile_id = mandate::helpers::get_profile_id_for_mandate( + state, + merchant_account, + mandate.clone(), + ) + .await?; + match resp.response { + Ok(types::PaymentsResponseData::TransactionResponse { .. }) => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + types::api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > = connector.connector.get_connector_integration(); + let merchant_connector_account = helpers::get_merchant_connector_account( + state, + &merchant_account.merchant_id, + None, + key_store, + &profile_id, + &mandate.connector, + mandate.merchant_connector_id.as_ref(), + ) + .await?; + + let router_data = mandate::utils::construct_mandate_revoke_router_data( + merchant_connector_account, + merchant_account, + mandate.clone(), + ) + .await?; + + let _response = services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + call_connector_action, + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + // TODO:Add the revoke mandate task to process tracker + mandate::update_mandate_procedure( + state, + resp, + mandate, + &merchant_account.merchant_id, + pm_id, + ) + .await + } + Ok(_) => Err(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Unexpected response received")?, + Err(_) => Ok(resp), + } + } else { + Err(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Update Mandate Flow not implemented for the connector ")? + } + } } impl mandate::MandateBehaviour for types::SetupMandateRequestData { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index e92a924bf12..6cf547f668f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1342,7 +1342,6 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsRejectDa }) } } - impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData { type Error = error_stack::Report<errors::ApiErrorResponse>; diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index b9119b0dbb8..14d119768d0 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -252,6 +252,13 @@ bank_debit.sepa = { connector_list = "gocardless"} bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +[mandates.update_mandate_supported] +card.credit ={connector_list ="cybersource"} +card.debit = {connector_list ="cybersource"} + +[mandates.update_mandate_supported] +connector_list = "cybersource" + [analytics] source = "sqlx"
2024-02-05T07:47:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description add config for update_mandate_flow and allow only those payment_methods that support update while Listing PaymentMethods For Merchants ### 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 an MA and a MCA for Cybersource > Create an update_,mandate payment using cyber source it'll be successful - Create an MA and a MCA forStripe > Create an update_,mandate payment using cyber source it should throw a 5xx - Now ListPaymentMethodsForMerchnat in an Update Flow, we only list cards ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ef302dd3983674c9df47812d3c398a7e7b423257
juspay/hyperswitch
juspay__hyperswitch-3457
Bug: [BUG] [HELCIM] 5XX Error Happening If Wrong Api Key Is Passed ### Bug Description If wrong `api_key` is passed during `Payment Connector - Create` for connector Helcim then the server throws 5XX error when you create a payment. ### Expected Behavior The connector should handle the error thrown during `Payments - Create` if wrong `api_key` is passed during `Payment Connector - Create` ### Actual Behavior The connector throws 5XX Error during `Payments - Create` if wrong `api_key` is passed during `Payment Connector - Create` ### 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 If wrong `api_key` is passed during `Payment Connector - Create` for connector Helcim then the server throws 5XX error when you create a payment. ### Environment SANDBOX ### 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/helcim.rs b/crates/router/src/connector/helcim.rs index c3a6c5e9f50..0b2cac5d766 100644 --- a/crates/router/src/connector/helcim.rs +++ b/crates/router/src/connector/helcim.rs @@ -128,9 +128,12 @@ impl ConnectorCommon for Helcim { .response .parse_struct("HelcimErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let error_string = match response.errors { - transformers::HelcimErrorTypes::StringType(error) => error, - transformers::HelcimErrorTypes::JsonType(error) => error.to_string(), + let error_string = match response { + transformers::HelcimErrorResponse::Payment(response) => match response.errors { + transformers::HelcimErrorTypes::StringType(error) => error, + transformers::HelcimErrorTypes::JsonType(error) => error.to_string(), + }, + transformers::HelcimErrorResponse::General(error_string) => error_string, }; Ok(ErrorResponse { diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index 599054163c3..5e076be651f 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -756,6 +756,13 @@ pub enum HelcimErrorTypes { } #[derive(Debug, Deserialize)] -pub struct HelcimErrorResponse { +pub struct HelcimPaymentsErrorResponse { pub errors: HelcimErrorTypes, } + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum HelcimErrorResponse { + Payment(HelcimPaymentsErrorResponse), + General(String), +}
2024-01-25T09:51:47Z
## 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 --> Earlier if wrong api_key is passed during Payment Connector - Create for connector Helcim then the server throws 5XX error when you create a payment. The connector will now handle the error thrown during Payments - Create if wrong api_key is passed during Payment Connector - Create. ### 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/3457 ## 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. Testing can be done by creating a payment with wrong api credentials. You should get the following error. ![Screenshot 2024-01-25 at 3 05 57 PM](https://github.com/juspay/hyperswitch/assets/41580413/a285179a-82b6-463d-8966-1e6ae58b8c5a) ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 210, "currency": "USD", "confirm": true, "capture_method": "automatic", "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": "1467", "zip": "94122", "first_name": "John", "last_name": "Doe" } }, "customer_id": "chethan" }' ``` 2. Testing for other error case like missing field error should also be done. You will get the following error: ![Screenshot 2024-01-25 at 3 28 13 PM](https://github.com/juspay/hyperswitch/assets/41580413/07d623ac-82af-4377-be43-a1e5420c55b1) ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 210, "currency": "USD", "confirm": true, "capture_method": "automatic", "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": "", "zip": "94122", "first_name": "John", "last_name": "Doe" } }, "customer_id": "chethan" }' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c2946cfe05ffa81a66643e04eff5e89b545d2d43
juspay/hyperswitch
juspay__hyperswitch-3454
Bug: fix(connector): fix connector template script In Recent changes, get_request_body return type was changed and connector template script was not modified .This pr fixes the connector template script. <img width="824" alt="Screenshot 2024-01-25 at 1 12 36 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/cf11184f-edd8-4c66-a6f3-8f40e2f7ddc7">
diff --git a/connector-template/mod.rs b/connector-template/mod.rs index 6258d437076..c64ce431968 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -167,10 +167,8 @@ impl req.request.amount, req, ))?; - let req_obj = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(&connector_router_data)?; - let {{project-name | downcase}}_req = types::RequestBody::log_and_get_request_body(&req_obj, utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::encode_to_string_of_json) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some({{project-name | downcase}}_req)) + let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -385,10 +383,8 @@ impl req.request.refund_amount, req, ))?; - let req_obj = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest::try_from(&connector_router_data)?; - let {{project-name | downcase}}_req = types::RequestBody::log_and_get_request_body(&req_obj, utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest>::encode_to_string_of_json) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some({{project-name | downcase}}_req)) + let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest::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> {
2024-01-25T07:18:33Z
## 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 --> In Recent changes, `get_request_body` return type was changed and connector template script was not modified .This pr fixes the connector template script. ### 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). --> In Recent changes of `get_request_body` return type was changed and connector template script was not modified .This pr fixes the connector template script. ## 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 `sh scripts/add_connector.sh example [<connector-base-url>](https://www.google.com/)` on oss branch and it should compile with no errors. <img width="1138" alt="Screenshot 2024-01-25 at 12 32 22 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/d4e75efc-5967-4b0f-8bc0-0f3bac0b955b"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b45e4ca2a3788823701bdeac2e2a8c1147bb071a
juspay/hyperswitch
juspay__hyperswitch-3448
Bug: [FIX] empty list of payment attempt on payments retrieve When you do a `PaymentsRetrieve` with a KV enabled merchant the `PaymentAttempts` list will be empty which is not expected
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index f8f752c6bc8..ce2c46bfe1d 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -931,12 +931,23 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } MerchantStorageScheme::RedisKv => { let key = format!("mid_{merchant_id}_pid_{payment_id}"); - - kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key) - .await - .change_context(errors::StorageError::KVError)? - .try_into_scan() - .change_context(errors::StorageError::KVError) + Box::pin(try_redis_get_else_try_database_get( + async { + kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key) + .await? + .try_into_scan() + }, + || async { + self.router_store + .find_attempts_by_merchant_id_payment_id( + merchant_id, + payment_id, + storage_scheme, + ) + .await + }, + )) + .await } } } diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 9339b11a9b9..ad57ad403d4 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -131,7 +131,16 @@ where } KvOperation::Scan(pattern) => { - let result: Vec<T> = redis_conn.hscan_and_deserialize(key, pattern, None).await?; + let result: Vec<T> = redis_conn + .hscan_and_deserialize(key, pattern, None) + .await + .and_then(|result| { + if result.is_empty() { + Err(RedisError::NotFound).into_report() + } else { + Ok(result) + } + })?; Ok(KvResult::Scan(result)) }
2024-01-24T10:22:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This fixes payments attempts being empty on `PaymentsRetrieve` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This fixes PaymentAttempts being empty on a case where data is directly inserted into the DB or the TTL has expired on Redis. ## 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 payment. - Do `PaymentsRetrieve` with `expand_attempts=true` ```bash curl --location 'http://localhost:8080/payments/pay_QJ9r33h2IiJz15brygDm?expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_6GYF6ws2zde4cDNPtKRKdLbYaY1Ekz3MtH2S9B8Zkb0aZIuXh4NlWICzdw5kTmHY'** ``` ## 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
3f343d36bff7ce8f73602a2391d205367d5581c7
juspay/hyperswitch
juspay__hyperswitch-3466
Bug: [REFACTOR] Make the function to deserialize hashsets more generic when deserializing application configs ### Description As of opening this issue, there are multiple functions to deserialize hashsets with similar logic. These functions can be made generic, and reduced to one common function for deserializing all types. Links to relevant functions: 1. https://github.com/juspay/hyperswitch/blob/0e4e18441d024b7d669b27d6f8a2feb3eccedb2a/crates/router/src/configs/settings.rs#L215-L242 2. https://github.com/juspay/hyperswitch/blob/0e4e18441d024b7d669b27d6f8a2feb3eccedb2a/crates/router/src/configs/settings.rs#L327-L355 3. https://github.com/juspay/hyperswitch/blob/0e4e18441d024b7d669b27d6f8a2feb3eccedb2a/crates/router/src/configs/settings.rs#L419-L469 4. https://github.com/juspay/hyperswitch/blob/0e4e18441d024b7d669b27d6f8a2feb3eccedb2a/crates/router/src/configs/settings.rs#L759-L772 In addition, the existing functions ignore any deserialization errors in case incorrect or unrecognized enum variants are provided, which causes the application to completely ignore those configuration entries. This would also have to be handled, to raise errors in case incorrect values are provided.
diff --git a/Cargo.lock b/Cargo.lock index 5623fd9f729..24fedf82a27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2603,9 +2603,9 @@ dependencies = [ [[package]] name = "fred" -version = "7.0.0" +version = "7.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2e8094c30c33132e948eb7e1b740cfdaa5a6702610bd3a2744002ec3575cd68" +checksum = "9282e65613822eea90c99872c51afa1de61542215cb11f91456a93f50a5a131a" dependencies = [ "arc-swap", "async-trait", @@ -2626,6 +2626,7 @@ dependencies = [ "tracing", "tracing-futures", "url", + "urlencoding", ] [[package]] @@ -5340,16 +5341,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "rust_decimal_macros" -version = "1.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e43721f4ef7060ebc2c3ede757733209564ca8207f47674181bcd425dd76945" -dependencies = [ - "quote", - "rust_decimal", -] - [[package]] name = "rustc-demangle" version = "0.1.23" @@ -5512,11 +5503,9 @@ dependencies = [ [[package]] name = "rusty-money" version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b28f881005eac7ad8d46b6f075da5f322bd7f4f83a38720fc069694ddadd683" +source = "git+https://github.com/varunsrin/rusty_money?rev=bbc0150742a0fff905225ff11ee09388e9babdcc#bbc0150742a0fff905225ff11ee09388e9babdcc" dependencies = [ "rust_decimal", - "rust_decimal_macros", ] [[package]] diff --git a/config/config.example.toml b/config/config.example.toml index 0ad50736e9e..3da1cd0daa0 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -415,7 +415,7 @@ alfamart = { country = "ID", currency = "IDR" } indomaret = { country = "ID", currency = "IDR" } open_banking_uk = { country = "GB", currency = "GBP" } oxxo = { country = "MX", currency = "MXN" } -pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } seven_eleven = { country = "JP", currency = "JPY" } lawson = { country = "JP", currency = "JPY" } mini_stop = { country = "JP", currency = "JPY" } @@ -452,7 +452,7 @@ connector_list = "gocardless,stax,stripe" payout_connector_list = "wise" [bank_config.online_banking_fpx] -adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" [bank_config.online_banking_thailand] adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 4a858588b50..d377b3359c9 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -4,7 +4,7 @@ eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" -online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24" online_banking_slovakia.adyen.banks = "e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo" online_banking_thailand.adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" @@ -133,20 +133,20 @@ giropay = { country = "DE", currency = "EUR" } google_pay.country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" ideal = { country = "NL", currency = "EUR" } klarna = { country = "AT,BE,DK,FI,FR,DE,IE,IT,NL,NO,ES,SE,GB,US,CA", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } -paypal.country = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" +paypal.currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } [pm_filters.adyen] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } alfamart = { country = "ID", currency = "IDR" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } ali_pay_hk = { country = "HK", currency = "HKD" } alma = { country = "FR", currency = "EUR" } -apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,UK,SE,NO,AK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,GB,SE,NO,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } atome = { country = "MY,SG", currency = "MYR,SGD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } bca_bank_transfer = { country = "ID", currency = "IDR" } bizum = { country = "ES", currency = "EUR" } @@ -162,11 +162,11 @@ family_mart = { country = "JP", currency = "JPY" } gcash = { country = "PH", currency = "PHP" } giropay = { country = "DE", currency = "EUR" } go_pay = { country = "ID", currency = "IDR" } -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -184,20 +184,20 @@ open_banking_uk = { country = "GB", currency = "GBP" } oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } -pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } twint = { country = "CH", currency = "CHF" } vipps = { country = "NO", currency = "NOK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD,CNY" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD,CNY" } [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 376ae579a50..d4671d3a99d 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -4,9 +4,9 @@ eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" -online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24" -online_banking_slovakia.adyen.banks = "e_platby_v_u_b,e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo,volksbank_gruppe,volkskredit_bank_ag,vr_bank_braunau" +online_banking_slovakia.adyen.banks = "e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" online_banking_thailand.adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" open_banking_uk.adyen.banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled" przelewy24.stripe.banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" @@ -127,17 +127,17 @@ payout_eligibility = true [pm_filters.default] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD,CNY" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD,CNY" } apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } blik = { country = "PL", currency = "PLN" } eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } mb_way = { country = "PT", currency = "EUR" } mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } online_banking_czech_republic = { country = "CZ", currency = "EUR,CZK" } @@ -145,24 +145,24 @@ online_banking_finland = { country = "FI", currency = "EUR" } online_banking_poland = { country = "PL", currency = "PLN" } online_banking_slovakia = { country = "SK", currency = "EUR,CZK" } pay_bright = { country = "CA", currency = "CAD" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } [pm_filters.adyen] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,CA,ES,FR,IT,NZ,UK,US", currency = "USD,AUD,CAD,NZD,GBP" } +afterpay_clearpay = { country = "AU,CA,ES,FR,IT,NZ,GB,US", currency = "USD,AUD,CAD,NZD,GBP" } alfamart = { country = "ID", currency = "IDR" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } ali_pay_hk = { country = "HK", currency = "HKD" } alma = { country = "FR", currency = "EUR" } -apple_pay = { country = "AE,AK,AM,AR,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CN,CO,CR,CY,CZ,DE,DK,EE,ES,FI,FO,FR,GB,GE,GG,GL,GR,HK,HR,HU,IE,IL,IM,IS,IT,JE,JO,JP,KW,KZ,LI,LT,LU,LV,MC,MD,ME,MO,MT,MX,MY,NL,NO,NZ,PE,PL,PS,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,TW,UA,UK,UM,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +apple_pay = { country = "AE,AM,AR,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CN,CO,CR,CY,CZ,DE,DK,EE,ES,FI,FO,FR,GB,GE,GG,GL,GR,HK,HR,HU,IE,IL,IM,IS,IT,JE,JO,JP,KW,KZ,LI,LT,LU,LV,MC,MD,ME,MO,MT,MX,MY,NL,NO,NZ,PE,PL,PS,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,TW,UA,GB,UM,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } atome = { country = "MY,SG", currency = "MYR,SGD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } bca_bank_transfer = { country = "ID", currency = "IDR" } bizum = { country = "ES", currency = "EUR" } @@ -178,11 +178,11 @@ family_mart = { country = "JP", currency = "JPY" } gcash = { country = "PH", currency = "PHP" } giropay = { country = "DE", currency = "EUR" } go_pay = { country = "ID", currency = "IDR" } -google_pay = { country = "AE,AG,AL,AO,AR,AS,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CL,CO,CY,CZ,DE,DK,DO,DZ,EE,EG,ES,FI,FR,GB,GR,HK,HR,HU,ID,IE,IL,IN,IS,IT,JO,JP,KE,KW,KZ,LB,LI,LK,LT,LU,LV,MT,MX,MY,NL,NO,NZ,OM,PA,PE,PH,PK,PL,PT,QA,RO,RU,SA,SE,SG,SI,SK,TH,TR,TW,UA,UK,US,UY,VN,ZA", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AE,AG,AL,AO,AR,AS,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CL,CO,CY,CZ,DE,DK,DO,DZ,EE,EG,ES,FI,FR,GB,GR,HK,HR,HU,ID,IE,IL,IN,IS,IT,JO,JP,KE,KW,KZ,LB,LI,LK,LT,LU,LV,MT,MX,MY,NL,NO,NZ,OM,PA,PE,PH,PK,PL,PT,QA,RO,RU,SA,SE,SG,SI,SK,TH,TR,TW,UA,GB,US,UY,VN,ZA", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,BE,CA,CH,DE,DK,ES,FI,FR,GB,IE,IT,NL,NO,PL,PT,SE,UK,US", currency = "AUD,CAD,CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD" } +klarna = { country = "AT,BE,CA,CH,DE,DK,ES,FI,FR,GB,IE,IT,NL,NO,PL,PT,SE,GB,US", currency = "AUD,CAD,CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD" } lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -200,20 +200,20 @@ open_banking_uk = { country = "GB", currency = "GBP" } oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } -pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE,UK", currency = "EUR" } +sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE,GB", currency = "EUR" } swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } twint = { country = "CH", currency = "CHF" } vipps = { country = "NO", currency = "NOK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 01616f3ecd0..abacd3ba5a1 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -4,7 +4,7 @@ eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" -online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24" online_banking_slovakia.adyen.banks = "e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo" online_banking_thailand.adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" @@ -127,17 +127,17 @@ payout_eligibility = true [pm_filters.default] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } blik = { country = "PL", currency = "PLN" } eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } mb_way = { country = "PT", currency = "EUR" } mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } online_banking_czech_republic = { country = "CZ", currency = "EUR,CZK" } @@ -145,24 +145,24 @@ online_banking_finland = { country = "FI", currency = "EUR" } online_banking_poland = { country = "PL", currency = "PLN" } online_banking_slovakia = { country = "SK", currency = "EUR,CZK" } pay_bright = { country = "CA", currency = "CAD" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } [pm_filters.adyen] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } alfamart = { country = "ID", currency = "IDR" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } ali_pay_hk = { country = "HK", currency = "HKD" } alma = { country = "FR", currency = "EUR" } -apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,UK,SE,NO,AK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,GB,SE,NO,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } atome = { country = "MY,SG", currency = "MYR,SGD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } bca_bank_transfer = { country = "ID", currency = "IDR" } bizum = { country = "ES", currency = "EUR" } @@ -178,11 +178,11 @@ family_mart = { country = "JP", currency = "JPY" } gcash = { country = "PH", currency = "PHP" } giropay = { country = "DE", currency = "EUR" } go_pay = { country = "ID", currency = "IDR" } -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -200,20 +200,20 @@ open_banking_uk = { country = "GB", currency = "GBP" } oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } -pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } twint = { country = "CH", currency = "CHF" } vipps = { country = "NO", currency = "NOK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/development.toml b/config/development.toml index b23f68680e6..15366986db5 100644 --- a/config/development.toml +++ b/config/development.toml @@ -263,7 +263,7 @@ stripe = { banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,ba adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled"} [bank_config.online_banking_fpx] -adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" [bank_config.online_banking_thailand] adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" @@ -293,31 +293,31 @@ ideal = { country = "NL", currency = "EUR" } cashapp = { country = "US", currency = "USD" } [pm_filters.adyen] -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } -apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,UK,SE,NO,AK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,GB,SE,NO,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } mb_way = { country = "PT", currency = "EUR" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } pay_bright = { country = "CA", currency = "CAD" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } giropay = { country = "DE", currency = "EUR" } eps = { country = "AT", currency = "EUR" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } blik = {country = "PL", currency = "PLN"} -trustly = {country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} +trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} online_banking_czech_republic = {country = "CZ", currency = "EUR,CZK"} online_banking_finland = {country = "FI", currency = "EUR"} online_banking_poland = {country = "PL", currency = "PLN"} online_banking_slovakia = {country = "SK", currency = "EUR,CZK"} bancontact_card = {country = "BE", currency = "EUR"} ach = {country = "US", currency = "USD"} -bacs = {country = "UK", currency = "GBP"} +bacs = {country = "GB", currency = "GBP"} sepa = {country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR"} ali_pay_hk = {country = "HK", currency = "HKD"} bizum = {country = "ES", currency = "EUR"} @@ -341,7 +341,7 @@ alfamart = {country = "ID", currency = "IDR"} indomaret = {country = "ID", currency = "IDR"} open_banking_uk = {country = "GB", currency = "GBP"} oxxo = {country = "MX", currency = "MXN"} -pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} +pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} seven_eleven = {country = "JP", currency = "JPY"} lawson = {country = "JP", currency = "JPY"} mini_stop = {country = "JP", currency = "JPY"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8af1528e177..7ad4f6e62ca 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -286,7 +286,7 @@ alfamart = {country = "ID", currency = "IDR"} indomaret = {country = "ID", currency = "IDR"} open_banking_uk = {country = "GB", currency = "GBP"} oxxo = {country = "MX", currency = "MXN"} -pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} +pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} seven_eleven = {country = "JP", currency = "JPY"} lawson = {country = "JP", currency = "JPY"} mini_stop = {country = "JP", currency = "JPY"} @@ -322,7 +322,7 @@ debit = { currency = "USD" } ach = { currency = "USD" } [bank_config.online_banking_fpx] -adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" [bank_config.online_banking_thailand] adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 949cc2e0034..6cf125be5cd 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -387,12 +387,15 @@ pub enum Currency { ALL, AMD, ANG, + AOA, ARS, AUD, AWG, AZN, + BAM, BBD, BDT, + BGN, BHD, BIF, BMD, @@ -401,6 +404,7 @@ pub enum Currency { BRL, BSD, BWP, + BYN, BZD, CAD, CHF, @@ -409,6 +413,7 @@ pub enum Currency { COP, CRC, CUP, + CVE, CZK, DJF, DKK, @@ -418,7 +423,9 @@ pub enum Currency { ETB, EUR, FJD, + FKP, GBP, + GEL, GHS, GIP, GMD, @@ -433,6 +440,7 @@ pub enum Currency { IDR, ILS, INR, + IQD, JMD, JOD, JPY, @@ -449,6 +457,7 @@ pub enum Currency { LKR, LRD, LSL, + LYD, MAD, MDL, MGA, @@ -456,11 +465,13 @@ pub enum Currency { MMK, MNT, MOP, + MRU, MUR, MVR, MWK, MXN, MYR, + MZN, NAD, NGN, NIO, @@ -468,6 +479,7 @@ pub enum Currency { NPR, NZD, OMR, + PAB, PEN, PGK, PHP, @@ -476,34 +488,47 @@ pub enum Currency { PYG, QAR, RON, + RSD, RUB, RWF, SAR, + SBD, SCR, SEK, SGD, + SHP, + SLE, SLL, SOS, + SRD, SSP, + STN, SVC, SZL, THB, + TND, + TOP, TRY, TTD, TWD, TZS, + UAH, UGX, #[default] USD, UYU, UZS, + VES, VND, VUV, + WST, XAF, + XCD, XOF, XPF, YER, ZAR, + ZMW, } impl Currency { @@ -560,12 +585,15 @@ impl Currency { Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", + Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", + Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", + Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", @@ -574,6 +602,7 @@ impl Currency { Self::BRL => "986", Self::BSD => "044", Self::BWP => "072", + Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CHF => "756", @@ -581,6 +610,7 @@ impl Currency { Self::COP => "170", Self::CRC => "188", Self::CUP => "192", + Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", @@ -590,7 +620,9 @@ impl Currency { Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", + Self::FKP => "238", Self::GBP => "826", + Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", @@ -605,6 +637,7 @@ impl Currency { Self::IDR => "360", Self::ILS => "376", Self::INR => "356", + Self::IQD => "368", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", @@ -621,6 +654,7 @@ impl Currency { Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", + Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", @@ -628,11 +662,13 @@ impl Currency { Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", + Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", + Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", @@ -640,6 +676,7 @@ impl Currency { Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", + Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", @@ -649,33 +686,46 @@ impl Currency { Self::QAR => "634", Self::RON => "946", Self::CNY => "156", + Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", + Self::SBD => "090", Self::SCR => "690", Self::SEK => "752", Self::SGD => "702", + Self::SHP => "654", + Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", + Self::SRD => "968", Self::SSP => "728", + Self::STN => "930", Self::SVC => "222", Self::SZL => "748", Self::THB => "764", + Self::TND => "788", + Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", + Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", + Self::VES => "928", Self::VND => "704", Self::VUV => "548", + Self::WST => "882", Self::XAF => "950", + Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", + Self::ZMW => "967", } } @@ -701,12 +751,15 @@ impl Currency { | Self::ALL | Self::AMD | Self::ANG + | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN + | Self::BAM | Self::BBD | Self::BDT + | Self::BGN | Self::BHD | Self::BMD | Self::BND @@ -714,6 +767,7 @@ impl Currency { | Self::BRL | Self::BSD | Self::BWP + | Self::BYN | Self::BZD | Self::CAD | Self::CHF @@ -721,6 +775,7 @@ impl Currency { | Self::COP | Self::CRC | Self::CUP + | Self::CVE | Self::CZK | Self::DKK | Self::DOP @@ -729,7 +784,9 @@ impl Currency { | Self::ETB | Self::EUR | Self::FJD + | Self::FKP | Self::GBP + | Self::GEL | Self::GHS | Self::GIP | Self::GMD @@ -743,6 +800,7 @@ impl Currency { | Self::IDR | Self::ILS | Self::INR + | Self::IQD | Self::JMD | Self::JOD | Self::KES @@ -756,17 +814,20 @@ impl Currency { | Self::LKR | Self::LRD | Self::LSL + | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP + | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR + | Self::MZN | Self::NAD | Self::NGN | Self::NIO @@ -774,6 +835,7 @@ impl Currency { | Self::NPR | Self::NZD | Self::OMR + | Self::PAB | Self::PEN | Self::PGK | Self::PHP @@ -781,42 +843,60 @@ impl Currency { | Self::PLN | Self::QAR | Self::RON + | Self::RSD | Self::RUB | Self::SAR + | Self::SBD | Self::SCR | Self::SEK | Self::SGD + | Self::SHP + | Self::SLE | Self::SLL | Self::SOS + | Self::SRD | Self::SSP + | Self::STN | Self::SVC | Self::SZL | Self::THB + | Self::TND + | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS + | Self::UAH | Self::USD | Self::UYU | Self::UZS + | Self::VES + | Self::WST + | Self::XCD | Self::YER - | Self::ZAR => false, + | Self::ZAR + | Self::ZMW => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { - Self::BHD | Self::JOD | Self::KWD | Self::OMR => true, + Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { + true + } Self::AED | Self::ALL | Self::AMD + | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN + | Self::BAM | Self::BBD | Self::BDT + | Self::BGN | Self::BIF | Self::BMD | Self::BND @@ -824,6 +904,7 @@ impl Currency { | Self::BRL | Self::BSD | Self::BWP + | Self::BYN | Self::BZD | Self::CAD | Self::CHF @@ -832,6 +913,7 @@ impl Currency { | Self::COP | Self::CRC | Self::CUP + | Self::CVE | Self::CZK | Self::DJF | Self::DKK @@ -841,7 +923,9 @@ impl Currency { | Self::ETB | Self::EUR | Self::FJD + | Self::FKP | Self::GBP + | Self::GEL | Self::GHS | Self::GIP | Self::GMD @@ -877,17 +961,20 @@ impl Currency { | Self::MMK | Self::MNT | Self::MOP + | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR + | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD + | Self::PAB | Self::PEN | Self::PGK | Self::PHP @@ -896,33 +983,45 @@ impl Currency { | Self::PYG | Self::QAR | Self::RON + | Self::RSD | Self::RUB | Self::RWF | Self::SAR + | Self::SBD | Self::SCR | Self::SEK | Self::SGD + | Self::SHP + | Self::SLE | Self::SLL | Self::SOS + | Self::SRD | Self::SSP + | Self::STN | Self::SVC | Self::SZL | Self::THB + | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS + | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS + | Self::VES | Self::VND | Self::VUV + | Self::WST | Self::XAF + | Self::XCD | Self::XPF | Self::XOF | Self::YER - | Self::ZAR => false, + | Self::ZAR + | Self::ZMW => false, } } } diff --git a/crates/currency_conversion/Cargo.toml b/crates/currency_conversion/Cargo.toml index d84956fe2f7..d2c99080bf6 100644 --- a/crates/currency_conversion/Cargo.toml +++ b/crates/currency_conversion/Cargo.toml @@ -11,6 +11,6 @@ common_enums = { version = "0.1.0", path = "../common_enums", package = "common_ # Third party crates rust_decimal = "1.29" -rusty-money = { version = "0.4.0", features = ["iso", "crypto"] } +rusty-money = { git = "https://github.com/varunsrin/rusty_money", rev = "bbc0150742a0fff905225ff11ee09388e9babdcc", features = ["iso", "crypto"] } serde = { version = "1.0.193", features = ["derive"] } thiserror = "1.0.43" diff --git a/crates/currency_conversion/src/types.rs b/crates/currency_conversion/src/types.rs index fec25b9fc60..a84520dca0a 100644 --- a/crates/currency_conversion/src/types.rs +++ b/crates/currency_conversion/src/types.rs @@ -81,12 +81,15 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::ALL => iso::ALL, Currency::AMD => iso::AMD, Currency::ANG => iso::ANG, + Currency::AOA => iso::AOA, Currency::ARS => iso::ARS, Currency::AUD => iso::AUD, Currency::AWG => iso::AWG, Currency::AZN => iso::AZN, + Currency::BAM => iso::BAM, Currency::BBD => iso::BBD, Currency::BDT => iso::BDT, + Currency::BGN => iso::BGN, Currency::BHD => iso::BHD, Currency::BIF => iso::BIF, Currency::BMD => iso::BMD, @@ -95,6 +98,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::BRL => iso::BRL, Currency::BSD => iso::BSD, Currency::BWP => iso::BWP, + Currency::BYN => iso::BYN, Currency::BZD => iso::BZD, Currency::CAD => iso::CAD, Currency::CHF => iso::CHF, @@ -103,6 +107,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::COP => iso::COP, Currency::CRC => iso::CRC, Currency::CUP => iso::CUP, + Currency::CVE => iso::CVE, Currency::CZK => iso::CZK, Currency::DJF => iso::DJF, Currency::DKK => iso::DKK, @@ -112,7 +117,9 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::ETB => iso::ETB, Currency::EUR => iso::EUR, Currency::FJD => iso::FJD, + Currency::FKP => iso::FKP, Currency::GBP => iso::GBP, + Currency::GEL => iso::GEL, Currency::GHS => iso::GHS, Currency::GIP => iso::GIP, Currency::GMD => iso::GMD, @@ -127,6 +134,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::IDR => iso::IDR, Currency::ILS => iso::ILS, Currency::INR => iso::INR, + Currency::IQD => iso::IQD, Currency::JMD => iso::JMD, Currency::JOD => iso::JOD, Currency::JPY => iso::JPY, @@ -143,6 +151,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::LKR => iso::LKR, Currency::LRD => iso::LRD, Currency::LSL => iso::LSL, + Currency::LYD => iso::LYD, Currency::MAD => iso::MAD, Currency::MDL => iso::MDL, Currency::MGA => iso::MGA, @@ -150,11 +159,13 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::MMK => iso::MMK, Currency::MNT => iso::MNT, Currency::MOP => iso::MOP, + Currency::MRU => iso::MRU, Currency::MUR => iso::MUR, Currency::MVR => iso::MVR, Currency::MWK => iso::MWK, Currency::MXN => iso::MXN, Currency::MYR => iso::MYR, + Currency::MZN => iso::MZN, Currency::NAD => iso::NAD, Currency::NGN => iso::NGN, Currency::NIO => iso::NIO, @@ -162,6 +173,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::NPR => iso::NPR, Currency::NZD => iso::NZD, Currency::OMR => iso::OMR, + Currency::PAB => iso::PAB, Currency::PEN => iso::PEN, Currency::PGK => iso::PGK, Currency::PHP => iso::PHP, @@ -170,32 +182,45 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::PYG => iso::PYG, Currency::QAR => iso::QAR, Currency::RON => iso::RON, + Currency::RSD => iso::RSD, Currency::RUB => iso::RUB, Currency::RWF => iso::RWF, Currency::SAR => iso::SAR, + Currency::SBD => iso::SBD, Currency::SCR => iso::SCR, Currency::SEK => iso::SEK, Currency::SGD => iso::SGD, + Currency::SHP => iso::SHP, + Currency::SLE => iso::SLE, Currency::SLL => iso::SLL, Currency::SOS => iso::SOS, + Currency::SRD => iso::SRD, Currency::SSP => iso::SSP, + Currency::STN => iso::STN, Currency::SVC => iso::SVC, Currency::SZL => iso::SZL, Currency::THB => iso::THB, + Currency::TND => iso::TND, + Currency::TOP => iso::TOP, Currency::TTD => iso::TTD, Currency::TRY => iso::TRY, Currency::TWD => iso::TWD, Currency::TZS => iso::TZS, + Currency::UAH => iso::UAH, Currency::UGX => iso::UGX, Currency::USD => iso::USD, Currency::UYU => iso::UYU, Currency::UZS => iso::UZS, + Currency::VES => iso::VES, Currency::VND => iso::VND, Currency::VUV => iso::VUV, + Currency::WST => iso::WST, Currency::XAF => iso::XAF, + Currency::XCD => iso::XCD, Currency::XOF => iso::XOF, Currency::XPF => iso::XPF, Currency::YER => iso::YER, Currency::ZAR => iso::ZAR, + Currency::ZMW => iso::ZMW, } } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index b1636418aa1..5bcb64fd875 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -312,12 +312,15 @@ impl IntoDirValue for api_enums::Currency { Self::ALL => Ok(dirval!(PaymentCurrency = ALL)), Self::AMD => Ok(dirval!(PaymentCurrency = AMD)), Self::ANG => Ok(dirval!(PaymentCurrency = ANG)), + Self::AOA => Ok(dirval!(PaymentCurrency = AOA)), Self::ARS => Ok(dirval!(PaymentCurrency = ARS)), Self::AUD => Ok(dirval!(PaymentCurrency = AUD)), Self::AWG => Ok(dirval!(PaymentCurrency = AWG)), Self::AZN => Ok(dirval!(PaymentCurrency = AZN)), + Self::BAM => Ok(dirval!(PaymentCurrency = BAM)), Self::BBD => Ok(dirval!(PaymentCurrency = BBD)), Self::BDT => Ok(dirval!(PaymentCurrency = BDT)), + Self::BGN => Ok(dirval!(PaymentCurrency = BGN)), Self::BHD => Ok(dirval!(PaymentCurrency = BHD)), Self::BIF => Ok(dirval!(PaymentCurrency = BIF)), Self::BMD => Ok(dirval!(PaymentCurrency = BMD)), @@ -326,6 +329,7 @@ impl IntoDirValue for api_enums::Currency { Self::BRL => Ok(dirval!(PaymentCurrency = BRL)), Self::BSD => Ok(dirval!(PaymentCurrency = BSD)), Self::BWP => Ok(dirval!(PaymentCurrency = BWP)), + Self::BYN => Ok(dirval!(PaymentCurrency = BYN)), Self::BZD => Ok(dirval!(PaymentCurrency = BZD)), Self::CAD => Ok(dirval!(PaymentCurrency = CAD)), Self::CHF => Ok(dirval!(PaymentCurrency = CHF)), @@ -334,6 +338,7 @@ impl IntoDirValue for api_enums::Currency { Self::COP => Ok(dirval!(PaymentCurrency = COP)), Self::CRC => Ok(dirval!(PaymentCurrency = CRC)), Self::CUP => Ok(dirval!(PaymentCurrency = CUP)), + Self::CVE => Ok(dirval!(PaymentCurrency = CVE)), Self::CZK => Ok(dirval!(PaymentCurrency = CZK)), Self::DJF => Ok(dirval!(PaymentCurrency = DJF)), Self::DKK => Ok(dirval!(PaymentCurrency = DKK)), @@ -343,7 +348,9 @@ impl IntoDirValue for api_enums::Currency { Self::ETB => Ok(dirval!(PaymentCurrency = ETB)), Self::EUR => Ok(dirval!(PaymentCurrency = EUR)), Self::FJD => Ok(dirval!(PaymentCurrency = FJD)), + Self::FKP => Ok(dirval!(PaymentCurrency = FKP)), Self::GBP => Ok(dirval!(PaymentCurrency = GBP)), + Self::GEL => Ok(dirval!(PaymentCurrency = GEL)), Self::GHS => Ok(dirval!(PaymentCurrency = GHS)), Self::GIP => Ok(dirval!(PaymentCurrency = GIP)), Self::GMD => Ok(dirval!(PaymentCurrency = GMD)), @@ -358,6 +365,7 @@ impl IntoDirValue for api_enums::Currency { Self::IDR => Ok(dirval!(PaymentCurrency = IDR)), Self::ILS => Ok(dirval!(PaymentCurrency = ILS)), Self::INR => Ok(dirval!(PaymentCurrency = INR)), + Self::IQD => Ok(dirval!(PaymentCurrency = IQD)), Self::JMD => Ok(dirval!(PaymentCurrency = JMD)), Self::JOD => Ok(dirval!(PaymentCurrency = JOD)), Self::JPY => Ok(dirval!(PaymentCurrency = JPY)), @@ -374,6 +382,7 @@ impl IntoDirValue for api_enums::Currency { Self::LKR => Ok(dirval!(PaymentCurrency = LKR)), Self::LRD => Ok(dirval!(PaymentCurrency = LRD)), Self::LSL => Ok(dirval!(PaymentCurrency = LSL)), + Self::LYD => Ok(dirval!(PaymentCurrency = LYD)), Self::MAD => Ok(dirval!(PaymentCurrency = MAD)), Self::MDL => Ok(dirval!(PaymentCurrency = MDL)), Self::MGA => Ok(dirval!(PaymentCurrency = MGA)), @@ -381,11 +390,13 @@ impl IntoDirValue for api_enums::Currency { Self::MMK => Ok(dirval!(PaymentCurrency = MMK)), Self::MNT => Ok(dirval!(PaymentCurrency = MNT)), Self::MOP => Ok(dirval!(PaymentCurrency = MOP)), + Self::MRU => Ok(dirval!(PaymentCurrency = MRU)), Self::MUR => Ok(dirval!(PaymentCurrency = MUR)), Self::MVR => Ok(dirval!(PaymentCurrency = MVR)), Self::MWK => Ok(dirval!(PaymentCurrency = MWK)), Self::MXN => Ok(dirval!(PaymentCurrency = MXN)), Self::MYR => Ok(dirval!(PaymentCurrency = MYR)), + Self::MZN => Ok(dirval!(PaymentCurrency = MZN)), Self::NAD => Ok(dirval!(PaymentCurrency = NAD)), Self::NGN => Ok(dirval!(PaymentCurrency = NGN)), Self::NIO => Ok(dirval!(PaymentCurrency = NIO)), @@ -393,6 +404,7 @@ impl IntoDirValue for api_enums::Currency { Self::NPR => Ok(dirval!(PaymentCurrency = NPR)), Self::NZD => Ok(dirval!(PaymentCurrency = NZD)), Self::OMR => Ok(dirval!(PaymentCurrency = OMR)), + Self::PAB => Ok(dirval!(PaymentCurrency = PAB)), Self::PEN => Ok(dirval!(PaymentCurrency = PEN)), Self::PGK => Ok(dirval!(PaymentCurrency = PGK)), Self::PHP => Ok(dirval!(PaymentCurrency = PHP)), @@ -401,33 +413,46 @@ impl IntoDirValue for api_enums::Currency { Self::PYG => Ok(dirval!(PaymentCurrency = PYG)), Self::QAR => Ok(dirval!(PaymentCurrency = QAR)), Self::RON => Ok(dirval!(PaymentCurrency = RON)), + Self::RSD => Ok(dirval!(PaymentCurrency = RSD)), Self::RUB => Ok(dirval!(PaymentCurrency = RUB)), Self::RWF => Ok(dirval!(PaymentCurrency = RWF)), Self::SAR => Ok(dirval!(PaymentCurrency = SAR)), + Self::SBD => Ok(dirval!(PaymentCurrency = SBD)), Self::SCR => Ok(dirval!(PaymentCurrency = SCR)), Self::SEK => Ok(dirval!(PaymentCurrency = SEK)), Self::SGD => Ok(dirval!(PaymentCurrency = SGD)), + Self::SHP => Ok(dirval!(PaymentCurrency = SHP)), + Self::SLE => Ok(dirval!(PaymentCurrency = SLE)), Self::SLL => Ok(dirval!(PaymentCurrency = SLL)), Self::SOS => Ok(dirval!(PaymentCurrency = SOS)), + Self::SRD => Ok(dirval!(PaymentCurrency = SRD)), Self::SSP => Ok(dirval!(PaymentCurrency = SSP)), + Self::STN => Ok(dirval!(PaymentCurrency = STN)), Self::SVC => Ok(dirval!(PaymentCurrency = SVC)), Self::SZL => Ok(dirval!(PaymentCurrency = SZL)), Self::THB => Ok(dirval!(PaymentCurrency = THB)), + Self::TND => Ok(dirval!(PaymentCurrency = TND)), + Self::TOP => Ok(dirval!(PaymentCurrency = TOP)), Self::TRY => Ok(dirval!(PaymentCurrency = TRY)), Self::TTD => Ok(dirval!(PaymentCurrency = TTD)), Self::TWD => Ok(dirval!(PaymentCurrency = TWD)), Self::TZS => Ok(dirval!(PaymentCurrency = TZS)), + Self::UAH => Ok(dirval!(PaymentCurrency = UAH)), Self::UGX => Ok(dirval!(PaymentCurrency = UGX)), Self::USD => Ok(dirval!(PaymentCurrency = USD)), Self::UYU => Ok(dirval!(PaymentCurrency = UYU)), Self::UZS => Ok(dirval!(PaymentCurrency = UZS)), + Self::VES => Ok(dirval!(PaymentCurrency = VES)), Self::VND => Ok(dirval!(PaymentCurrency = VND)), Self::VUV => Ok(dirval!(PaymentCurrency = VUV)), + Self::WST => Ok(dirval!(PaymentCurrency = WST)), Self::XAF => Ok(dirval!(PaymentCurrency = XAF)), + Self::XCD => Ok(dirval!(PaymentCurrency = XCD)), Self::XOF => Ok(dirval!(PaymentCurrency = XOF)), Self::XPF => Ok(dirval!(PaymentCurrency = XPF)), Self::YER => Ok(dirval!(PaymentCurrency = YER)), Self::ZAR => Ok(dirval!(PaymentCurrency = ZAR)), + Self::ZMW => Ok(dirval!(PaymentCurrency = ZMW)), } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3c1d9f7d397..f186af60a9b 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -1,7 +1,6 @@ use std::{ collections::{HashMap, HashSet}, path::PathBuf, - str::FromStr, }; #[cfg(feature = "olap")] @@ -19,7 +18,7 @@ use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; use scheduler::SchedulerSettings; -use serde::{de::Error, Deserialize, Deserializer}; +use serde::Deserialize; use storage_impl::config::QueueStrategy; #[cfg(feature = "olap")] @@ -191,7 +190,7 @@ pub struct ApplepayMerchantConfigs { #[derive(Debug, Deserialize, Clone, Default)] pub struct MultipleApiVersionSupportedConnectors { - #[serde(deserialize_with = "connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub supported_connectors: HashSet<api_models::enums::Connector>, } @@ -205,42 +204,13 @@ pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMet #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorCustomer { - #[serde(deserialize_with = "connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<api_models::enums::Connector>, #[cfg(feature = "payouts")] - #[serde(deserialize_with = "payout_connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub payout_connector_list: HashSet<api_models::enums::PayoutConnectors>, } -fn connector_deser<'a, D>( - deserializer: D, -) -> Result<HashSet<api_models::enums::Connector>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - Ok(value - .trim() - .split(',') - .flat_map(api_models::enums::Connector::from_str) - .collect()) -} - -#[cfg(feature = "payouts")] -fn payout_connector_deser<'a, D>( - deserializer: D, -) -> Result<HashSet<api_models::enums::PayoutConnectors>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - Ok(value - .trim() - .split(',') - .flat_map(api_models::enums::PayoutConnectors::from_str) - .collect()) -} - #[cfg(feature = "dummy_connector")] #[derive(Debug, Deserialize, Clone, Default)] pub struct DummyConnector { @@ -281,13 +251,13 @@ pub struct SupportedPaymentMethodTypesForMandate( #[derive(Debug, Deserialize, Clone)] pub struct SupportedConnectorsForMandate { - #[serde(deserialize_with = "connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<api_models::enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodTokenFilter { - #[serde(deserialize_with = "pm_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, pub payment_method_type: Option<PaymentMethodTypeTokenFilter>, pub long_lived_token: bool, @@ -304,7 +274,7 @@ pub enum ApplePayPreDecryptFlow { #[derive(Debug, Deserialize, Clone, Default)] pub struct TempLockerEnablePaymentMethodFilter { - #[serde(deserialize_with = "pm_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, } @@ -316,44 +286,14 @@ pub struct TempLockerEnablePaymentMethodFilter { rename_all = "snake_case" )] pub enum PaymentMethodTypeTokenFilter { - #[serde(deserialize_with = "pm_type_deser")] + #[serde(deserialize_with = "deserialize_hashset")] EnableOnly(HashSet<diesel_models::enums::PaymentMethodType>), - #[serde(deserialize_with = "pm_type_deser")] + #[serde(deserialize_with = "deserialize_hashset")] DisableOnly(HashSet<diesel_models::enums::PaymentMethodType>), #[default] AllAccepted, } -fn pm_deser<'a, D>( - deserializer: D, -) -> Result<HashSet<diesel_models::enums::PaymentMethod>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - value - .trim() - .split(',') - .map(diesel_models::enums::PaymentMethod::from_str) - .collect::<Result<_, _>>() - .map_err(D::Error::custom) -} - -fn pm_type_deser<'a, D>( - deserializer: D, -) -> Result<HashSet<diesel_models::enums::PaymentMethodType>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - value - .trim() - .split(',') - .map(diesel_models::enums::PaymentMethodType::from_str) - .collect::<Result<_, _>>() - .map_err(D::Error::custom) -} - #[derive(Debug, Deserialize, Clone, Default)] pub struct BankRedirectConfig( pub HashMap<api_models::enums::PaymentMethodType, ConnectorBankNames>, @@ -363,7 +303,7 @@ pub struct ConnectorBankNames(pub HashMap<String, BanksVector>); #[derive(Debug, Deserialize, Clone)] pub struct BanksVector { - #[serde(deserialize_with = "bank_vec_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub banks: HashSet<api_models::enums::BankNames>, } @@ -385,9 +325,9 @@ pub enum PaymentMethodFilterKey { #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { - #[serde(deserialize_with = "currency_set_deser")] + #[serde(deserialize_with = "deserialize_optional_hashset")] pub currency: Option<HashSet<api_models::enums::Currency>>, - #[serde(deserialize_with = "string_set_deser")] + #[serde(deserialize_with = "deserialize_optional_hashset")] pub country: Option<HashSet<api_models::enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } @@ -416,58 +356,6 @@ pub struct RequiredFieldFinal { pub common: HashMap<String, RequiredFieldInfo>, } -fn string_set_deser<'a, D>( - deserializer: D, -) -> Result<Option<HashSet<api_models::enums::CountryAlpha2>>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <Option<String>>::deserialize(deserializer)?; - Ok(value.and_then(|inner| { - let list = inner - .trim() - .split(',') - .flat_map(api_models::enums::CountryAlpha2::from_str) - .collect::<HashSet<_>>(); - match list.len() { - 0 => None, - _ => Some(list), - } - })) -} - -fn currency_set_deser<'a, D>( - deserializer: D, -) -> Result<Option<HashSet<api_models::enums::Currency>>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <Option<String>>::deserialize(deserializer)?; - Ok(value.and_then(|inner| { - let list = inner - .trim() - .split(',') - .flat_map(api_models::enums::Currency::from_str) - .collect::<HashSet<_>>(); - match list.len() { - 0 => None, - _ => Some(list), - } - })) -} - -fn bank_vec_deser<'a, D>(deserializer: D) -> Result<HashSet<api_models::enums::BankNames>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - Ok(value - .trim() - .split(',') - .flat_map(api_models::enums::BankNames::from_str) - .collect()) -} - #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct Secrets { @@ -733,13 +621,13 @@ pub struct FileUploadConfig { #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { - #[serde(deserialize_with = "deser_to_get_connectors")] + #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_delayed_session_response: HashSet<api_models::enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct WebhookSourceVerificationCall { - #[serde(deserialize_with = "connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_webhook_source_verification_call: HashSet<api_models::enums::Connector>, } @@ -756,21 +644,6 @@ pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>, } -fn deser_to_get_connectors<'a, D>( - deserializer: D, -) -> Result<HashSet<api_models::enums::Connector>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - value - .trim() - .split(',') - .map(api_models::enums::Connector::from_str) - .collect::<Result<_, _>>() - .map_err(D::Error::custom) -} - impl Settings { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) @@ -861,24 +734,6 @@ impl Settings { } } -#[cfg(test)] -mod payment_method_deserialization_test { - #![allow(clippy::unwrap_used)] - use serde::de::{ - value::{Error as ValueError, StrDeserializer}, - IntoDeserializer, - }; - - use super::*; - - #[test] - fn test_pm_deserializer() { - let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer(); - let test_pm = pm_deser(deserializer); - assert!(test_pm.is_ok()) - } -} - #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Clone, Default)] pub struct Payouts { @@ -893,7 +748,7 @@ pub struct LockSettings { } impl<'de> Deserialize<'de> for LockSettings { - fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Inner { @@ -928,3 +783,124 @@ pub struct PayPalOnboarding { pub partner_id: masking::Secret<String>, pub enabled: bool, } + +fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> +where + T: Eq + std::str::FromStr + std::hash::Hash, + <T as std::str::FromStr>::Err: std::fmt::Display, +{ + let (values, errors) = value + .as_ref() + .trim() + .split(',') + .map(|s| { + T::from_str(s.trim()).map_err(|error| { + format!( + "Unable to deserialize `{}` as `{}`: {error}", + s.trim(), + std::any::type_name::<T>() + ) + }) + }) + .fold( + (HashSet::new(), Vec::new()), + |(mut values, mut errors), result| match result { + Ok(t) => { + values.insert(t); + (values, errors) + } + Err(error) => { + errors.push(error); + (values, errors) + } + }, + ); + if !errors.is_empty() { + Err(format!("Some errors occurred:\n{}", errors.join("\n"))) + } else { + Ok(values) + } +} + +fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error> +where + D: serde::Deserializer<'a>, + T: Eq + std::str::FromStr + std::hash::Hash, + <T as std::str::FromStr>::Err: std::fmt::Display, +{ + use serde::de::Error; + + deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom) +} + +fn deserialize_optional_hashset<'a, D, T>(deserializer: D) -> Result<Option<HashSet<T>>, D::Error> +where + D: serde::Deserializer<'a>, + T: Eq + std::str::FromStr + std::hash::Hash, + <T as std::str::FromStr>::Err: std::fmt::Display, +{ + use serde::de::Error; + + <Option<String>>::deserialize(deserializer).map(|value| { + value.map_or(Ok(None), |inner: String| { + let list = deserialize_hashset_inner(inner).map_err(D::Error::custom)?; + match list.len() { + 0 => Ok(None), + _ => Ok(Some(list)), + } + }) + })? +} + +#[cfg(test)] +mod hashset_deserialization_test { + #![allow(clippy::unwrap_used)] + use std::collections::HashSet; + + use serde::de::{ + value::{Error as ValueError, StrDeserializer}, + IntoDeserializer, + }; + + use super::deserialize_hashset; + + #[test] + fn test_payment_method_hashset_deserializer() { + use diesel_models::enums::PaymentMethod; + + let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer(); + let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); + let expected_payment_methods = HashSet::from([PaymentMethod::Wallet, PaymentMethod::Card]); + + assert!(payment_methods.is_ok()); + assert_eq!(payment_methods.unwrap(), expected_payment_methods); + } + + #[test] + fn test_payment_method_hashset_deserializer_with_spaces() { + use diesel_models::enums::PaymentMethod; + + let deserializer: StrDeserializer<'_, ValueError> = + "wallet, card, bank_debit".into_deserializer(); + let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); + let expected_payment_methods = HashSet::from([ + PaymentMethod::Wallet, + PaymentMethod::Card, + PaymentMethod::BankDebit, + ]); + + assert!(payment_methods.is_ok()); + assert_eq!(payment_methods.unwrap(), expected_payment_methods); + } + + #[test] + fn test_payment_method_hashset_deserializer_error() { + use diesel_models::enums::PaymentMethod; + + let deserializer: StrDeserializer<'_, ValueError> = + "wallet, card, unknown".into_deserializer(); + let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); + + assert!(payment_methods.is_err()); + } +} diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 135ca638109..604a3c5dab3 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5062,12 +5062,15 @@ "ALL", "AMD", "ANG", + "AOA", "ARS", "AUD", "AWG", "AZN", + "BAM", "BBD", "BDT", + "BGN", "BHD", "BIF", "BMD", @@ -5076,6 +5079,7 @@ "BRL", "BSD", "BWP", + "BYN", "BZD", "CAD", "CHF", @@ -5084,6 +5088,7 @@ "COP", "CRC", "CUP", + "CVE", "CZK", "DJF", "DKK", @@ -5093,7 +5098,9 @@ "ETB", "EUR", "FJD", + "FKP", "GBP", + "GEL", "GHS", "GIP", "GMD", @@ -5108,6 +5115,7 @@ "IDR", "ILS", "INR", + "IQD", "JMD", "JOD", "JPY", @@ -5124,6 +5132,7 @@ "LKR", "LRD", "LSL", + "LYD", "MAD", "MDL", "MGA", @@ -5131,11 +5140,13 @@ "MMK", "MNT", "MOP", + "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", + "MZN", "NAD", "NGN", "NIO", @@ -5143,6 +5154,7 @@ "NPR", "NZD", "OMR", + "PAB", "PEN", "PGK", "PHP", @@ -5151,33 +5163,46 @@ "PYG", "QAR", "RON", + "RSD", "RUB", "RWF", "SAR", + "SBD", "SCR", "SEK", "SGD", + "SHP", + "SLE", "SLL", "SOS", + "SRD", "SSP", + "STN", "SVC", "SZL", "THB", + "TND", + "TOP", "TRY", "TTD", "TWD", "TZS", + "UAH", "UGX", "USD", "UYU", "UZS", + "VES", "VND", "VUV", + "WST", "XAF", + "XCD", "XOF", "XPF", "YER", - "ZAR" + "ZAR", + "ZMW" ] }, "CustomerAcceptance": {
2023-12-11T11:34:43Z
## 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 updates the application configuration deserialization logic to use a common generic function to deserialize `HashSet<T>` instead of specific ones. In addition, this PR updates the function to be more lenient in that it allows spaces around the commas for better readability. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #3466. ## 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)? --> Unit tests: ```shell cargo test --package router --lib --all-features -- configs::settings::hashset_deserialization_test ``` <img width="800" alt="Screenshot of unit tests run" src="https://github.com/juspay/hyperswitch/assets/22217505/ac1de2b4-f771-44c7-87a9-03e62e8904f6"> Also, ran the application with each of the modified config files to verify that the application is able to correctly deserialize the specified config entries. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
98bf8f5b85d318cd6ad3c7105fdde3149a2ef8ed
juspay/hyperswitch
juspay__hyperswitch-3443
Bug: [REFACTOR] Inclusion of kill switch in `configs` table ## Description This refactor will ensure to be presence of a kill switch(merchant-wise) for Blocklist Feature. We will always check for a Boolean entry in `configs` table i.e `guard_blocklist_for_{merchant_id}` and all the blocklist flows(validation & fingerprint generation) will only run if the variable is set to be true. Else if the data is not present it will take it false(as default) and blocklist flows will be disabled. ## Testing steps ### For testing when the blocklist flows are disabled(That are by default) : ``` 1. Create a payment 2. Confirm it After a successful confirm the `fingerprint` entry in the response should be null. ``` ### For testing when the blocklist flows are enabled : ``` 1. Set/Create the entry `guard_blocklist_for_{merchant_id}` in configs table and set it to true. ``` After this all further testing steps can be followed from the parent [issue](https://github.com/juspay/hyperswitch/issues/3344)
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index c81145c5de7..eba32ca0a53 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -719,156 +719,175 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> let m_db = state.clone().store; // Validate Blocklist + let mut fingerprint_id = None; + let mut is_pm_blocklisted = false; let merchant_id = payment_data.payment_attempt.merchant_id; - let merchant_fingerprint_secret = - blocklist_utils::get_merchant_fingerprint_secret(state, &merchant_id).await?; - - // Hashed Fingerprint to check whether or not this payment should be blocked. - let card_number_fingerprint = payment_data - .payment_method_data - .as_ref() - .and_then(|pm_data| match pm_data { - api_models::payments::PaymentMethodData::Card(card) => { - crypto::HmacSha512::sign_message( - &crypto::HmacSha512, - merchant_fingerprint_secret.as_bytes(), - card.card_number.clone().get_card_no().as_bytes(), - ) - .attach_printable("error in pm fingerprint creation") - .map_or_else( - |err| { - logger::error!(error=?err); - None - }, - Some, - ) - } - _ => None, - }) - .map(hex::encode); + let blocklist_enabled_key = format!("guard_blocklist_for_{merchant_id}"); + let blocklist_guard_enabled = state + .store + .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string())) + .await; - // Hashed Cardbin to check whether or not this payment should be blocked. - let card_bin_fingerprint = payment_data - .payment_method_data - .as_ref() - .and_then(|pm_data| match pm_data { - api_models::payments::PaymentMethodData::Card(card) => { - crypto::HmacSha512::sign_message( - &crypto::HmacSha512, - merchant_fingerprint_secret.as_bytes(), - card.card_number.clone().get_card_isin().as_bytes(), - ) - .attach_printable("error in card bin hash creation") - .map_or_else( - |err| { - logger::error!(error=?err); - None - }, - Some, - ) - } - _ => None, - }) - .map(hex::encode); + let blocklist_guard_enabled: bool = match blocklist_guard_enabled { + Ok(config) => serde_json::from_str(&config.config).unwrap_or(false), - // Hashed Extended Cardbin to check whether or not this payment should be blocked. - let extended_card_bin_fingerprint = payment_data - .payment_method_data - .as_ref() - .and_then(|pm_data| match pm_data { - api_models::payments::PaymentMethodData::Card(card) => { - crypto::HmacSha512::sign_message( - &crypto::HmacSha512, - merchant_fingerprint_secret.as_bytes(), - card.card_number.clone().get_extended_card_bin().as_bytes(), - ) - .attach_printable("error in extended card bin hash creation") - .map_or_else( - |err| { - logger::error!(error=?err); - None - }, - Some, - ) + // If it is not present in db we are defaulting it to false + Err(inner) => { + if !inner.current_context().is_db_not_found() { + logger::error!("Error fetching guard blocklist enabled config {:?}", inner); } - _ => None, - }) - .map(hex::encode); - - let mut fingerprint_id = None; - - //validating the payment method. - let mut is_pm_blocklisted = false; + false + } + }; - let mut blocklist_futures = Vec::new(); - if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() { - blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( - &merchant_id, - card_number_fingerprint, - )); - } + if blocklist_guard_enabled { + let merchant_fingerprint_secret = + blocklist_utils::get_merchant_fingerprint_secret(state, &merchant_id).await?; + // Hashed Fingerprint to check whether or not this payment should be blocked. + let card_number_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_card_no().as_bytes(), + ) + .attach_printable("error in pm fingerprint creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + // Hashed Cardbin to check whether or not this payment should be blocked. + let card_bin_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_card_isin().as_bytes(), + ) + .attach_printable("error in card bin hash creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + // Hashed Extended Cardbin to check whether or not this payment should be blocked. + let extended_card_bin_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_extended_card_bin().as_bytes(), + ) + .attach_printable("error in extended card bin hash creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + //validating the payment method. + let mut blocklist_futures = Vec::new(); + if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + card_number_fingerprint, + )); + } - if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() { - blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( - &merchant_id, - card_bin_fingerprint, - )); - } + if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + card_bin_fingerprint, + )); + } - if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() { - blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( - &merchant_id, - extended_card_bin_fingerprint, - )); - } + if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + extended_card_bin_fingerprint, + )); + } - let blocklist_lookups = futures::future::join_all(blocklist_futures).await; + let blocklist_lookups = futures::future::join_all(blocklist_futures).await; - if blocklist_lookups.iter().any(|x| x.is_ok()) { - intent_status = storage_enums::IntentStatus::Failed; - attempt_status = storage_enums::AttemptStatus::Failure; - is_pm_blocklisted = true; - } + if blocklist_lookups.iter().any(|x| x.is_ok()) { + intent_status = storage_enums::IntentStatus::Failed; + attempt_status = storage_enums::AttemptStatus::Failure; + is_pm_blocklisted = true; + } - if let Some(encoded_hash) = card_number_fingerprint { - #[cfg(feature = "kms")] - let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms) - .await - .encrypt(encoded_hash) - .await - .map_or_else( - |e| { - logger::error!(error=?e, "failed kms encryption of card fingerprint"); - None - }, - Some, - ); - - #[cfg(not(feature = "kms"))] - let encrypted_fingerprint = Some(encoded_hash); - - if let Some(encrypted_fingerprint) = encrypted_fingerprint { - fingerprint_id = db - .insert_blocklist_fingerprint_entry( - diesel_models::blocklist_fingerprint::BlocklistFingerprintNew { - merchant_id, - fingerprint_id: utils::generate_id(consts::ID_LENGTH, "fingerprint"), - encrypted_fingerprint, - data_kind: common_enums::BlocklistDataKind::PaymentMethod, - created_at: common_utils::date_time::now(), - }, - ) + if let Some(encoded_hash) = card_number_fingerprint { + #[cfg(feature = "kms")] + let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + .await + .encrypt(encoded_hash) .await .map_or_else( |e| { - logger::error!(error=?e, "failed storing card fingerprint in db"); + logger::error!(error=?e, "failed kms encryption of card fingerprint"); None }, - |fp| Some(fp.fingerprint_id), + Some, ); + + #[cfg(not(feature = "kms"))] + let encrypted_fingerprint = Some(encoded_hash); + + if let Some(encrypted_fingerprint) = encrypted_fingerprint { + fingerprint_id = db + .insert_blocklist_fingerprint_entry( + diesel_models::blocklist_fingerprint::BlocklistFingerprintNew { + merchant_id, + fingerprint_id: utils::generate_id( + consts::ID_LENGTH, + "fingerprint", + ), + encrypted_fingerprint, + data_kind: common_enums::BlocklistDataKind::PaymentMethod, + created_at: common_utils::date_time::now(), + }, + ) + .await + .map_or_else( + |e| { + logger::error!(error=?e, "failed storing card fingerprint in db"); + None + }, + |fp| Some(fp.fingerprint_id), + ); + } } } - let surcharge_amount = payment_data .surcharge_details .as_ref()
2024-01-25T10:04:30Z
## 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 will allow us to enable and disable the blocklist feature based on each merchant's requirements. The steps to test out this feature can be found in the mentioned 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)? --> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
61439533594f93287f15aaffb5d65ed12e77e7ec
juspay/hyperswitch
juspay__hyperswitch-3440
Bug: [FEATURE] Add `KMS` encrypt utility ### Feature Description Introducing a new functionality, that seamlessly integrates with Key Management Service (KMS), offering a robust encryption solution. This feature empowers users to encrypt any value with ease, ensuring enhanced security and data protection. Leveraging KMS, the function provides a reliable and scalable approach to safeguard sensitive information, making it a valuable addition for bolstering the overall security posture of our application. ### Testing <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test cases written for encrpyt as well as decrypt functions. <img width="1400" alt="Screenshot 2023-12-12 at 13 33 03" src="https://github.com/juspay/hyperswitch/assets/61520228/638b199f-15ac-473e-84f5-55c3d8353715">
diff --git a/crates/external_services/src/kms.rs b/crates/external_services/src/kms.rs index 31c82253fe8..04a58e4b23f 100644 --- a/crates/external_services/src/kms.rs +++ b/crates/external_services/src/kms.rs @@ -75,7 +75,7 @@ impl KmsClient { // Logging using `Debug` representation of the error as the `Display` // representation does not hold sufficient information. logger::error!(kms_sdk_error=?error, "Failed to KMS decrypt data"); - metrics::AWS_KMS_FAILURES.add(&metrics::CONTEXT, 1, &[]); + metrics::AWS_KMS_DECRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); error }) .into_report() @@ -96,11 +96,51 @@ impl KmsClient { Ok(output) } + + /// Encrypts the provided String data using the AWS KMS SDK. We assume that + /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and + /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in + /// a machine that is able to assume an IAM role. + pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, KmsError> { + let start = Instant::now(); + let plaintext_blob = Blob::new(data.as_ref()); + + let encrypted_output = self + .inner_client + .encrypt() + .key_id(&self.key_id) + .plaintext(plaintext_blob) + .send() + .await + .map_err(|error| { + // Logging using `Debug` representation of the error as the `Display` + // representation does not hold sufficient information. + logger::error!(kms_sdk_error=?error, "Failed to KMS encrypt data"); + metrics::AWS_KMS_ENCRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); + error + }) + .into_report() + .change_context(KmsError::EncryptionFailed)?; + + let output = encrypted_output + .ciphertext_blob + .ok_or(KmsError::MissingCiphertextEncryptionOutput) + .into_report() + .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?; + let time_taken = start.elapsed(); + metrics::AWS_KMS_ENCRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]); + + Ok(output) + } } /// Errors that could occur during KMS operations. #[derive(Debug, thiserror::Error)] pub enum KmsError { + /// An error occurred when base64 encoding input data. + #[error("Failed to base64 encode input data")] + Base64EncodingFailed, + /// An error occurred when base64 decoding input data. #[error("Failed to base64 decode input data")] Base64DecodingFailed, @@ -109,10 +149,18 @@ pub enum KmsError { #[error("Failed to KMS decrypt input data")] DecryptionFailed, + /// An error occurred when KMS encrypting input data. + #[error("Failed to KMS encrypt input data")] + EncryptionFailed, + /// The KMS decrypted output does not include a plaintext output. #[error("Missing plaintext KMS decryption output")] MissingPlaintextDecryptionOutput, + /// The KMS encrypted output does not include a ciphertext output. + #[error("Missing ciphertext KMS encryption output")] + MissingCiphertextEncryptionOutput, + /// An error occurred UTF-8 decoding KMS decrypted output. #[error("Failed to UTF-8 decode decryption output")] Utf8DecodingFailed, @@ -147,3 +195,50 @@ impl common_utils::ext_traits::ConfigExt for KmsValue { self.0.peek().is_empty_after_trim() } } + +#[cfg(test)] +mod tests { + #![allow(clippy::expect_used)] + #[tokio::test] + async fn check_kms_encryption() { + std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); + std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); + use super::*; + let config = KmsConfig { + key_id: "YOUR KMS KEY ID".to_string(), + region: "AWS REGION".to_string(), + }; + + let data = "hello".to_string(); + let binding = data.as_bytes(); + let kms_encrypted_fingerprint = KmsClient::new(&config) + .await + .encrypt(binding) + .await + .expect("kms encryption failed"); + + println!("{}", kms_encrypted_fingerprint); + } + + #[tokio::test] + async fn check_kms_decrypt() { + std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); + std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); + use super::*; + let config = KmsConfig { + key_id: "YOUR KMS KEY ID".to_string(), + region: "AWS REGION".to_string(), + }; + + // Should decrypt to hello + let data = "KMS ENCRYPTED CIPHER".to_string(); + let binding = data.as_bytes(); + let kms_encrypted_fingerprint = KmsClient::new(&config) + .await + .decrypt(binding) + .await + .expect("kms decryption failed"); + + println!("{}", kms_encrypted_fingerprint); + } +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index fa57a0bac9c..ccf1db47a3a 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -26,8 +26,12 @@ pub mod metrics { global_meter!(GLOBAL_METER, "EXTERNAL_SERVICES"); #[cfg(feature = "kms")] - counter_metric!(AWS_KMS_FAILURES, GLOBAL_METER); // No. of AWS KMS API failures + counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures + #[cfg(feature = "kms")] + counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures #[cfg(feature = "kms")] histogram_metric!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for KMS decryption time (in sec) + #[cfg(feature = "kms")] + histogram_metric!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for KMS encryption time (in sec) } diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 192df1a0929..b3629ab7d52 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -6,7 +6,9 @@ global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses #[cfg(feature = "kms")] -counter_metric!(AWS_KMS_FAILURES, GLOBAL_METER); // No. of AWS KMS API failures +counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures +#[cfg(feature = "kms")] +counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures // API Level Metrics counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER);
2023-12-12T08:15:43Z
## 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 --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## 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)? --> Test cases written for encrpyt as well as decrypt functions. <img width="1400" alt="Screenshot 2023-12-12 at 13 33 03" src="https://github.com/juspay/hyperswitch/assets/61520228/638b199f-15ac-473e-84f5-55c3d8353715"> ## 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 - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1add2c059f4fb5653f33e2f3ce454793caf2d595
juspay/hyperswitch
juspay__hyperswitch-3441
Bug: [DOCS] Add Api-Refrence for Blocklist This PR adds the api contracts(utoipa) for all blocklist apis.
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs index fc838eed5ce..888b9106ccc 100644 --- a/crates/api_models/src/blocklist.rs +++ b/crates/api_models/src/blocklist.rs @@ -1,7 +1,8 @@ use common_enums::enums; use common_utils::events::ApiEventMetric; +use utoipa::ToSchema; -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "data")] pub enum BlocklistRequest { CardBin(String), @@ -12,9 +13,10 @@ pub enum BlocklistRequest { pub type AddToBlocklistRequest = BlocklistRequest; pub type DeleteFromBlocklistRequest = BlocklistRequest; -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BlocklistResponse { pub fingerprint_id: String, + #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, @@ -23,8 +25,9 @@ pub struct BlocklistResponse { pub type AddToBlocklistResponse = BlocklistResponse; pub type DeleteFromBlocklistResponse = BlocklistResponse; -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ListBlocklistQuery { + #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(default = "default_list_limit")] pub limit: u16, diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rs index c263bef63c5..93361552de7 100644 --- a/crates/router/src/db/blocklist.rs +++ b/crates/router/src/db/blocklist.rs @@ -163,41 +163,49 @@ impl BlocklistInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, - _pm_blocklist: storage::BlocklistNew, + pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store.insert_blocklist_entry(pm_blocklist).await } async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, - _merchant_id: &str, - _fingerprint_id: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) + .await } async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, - _merchant_id: &str, - _fingerprint_id: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) + .await } async fn list_blocklist_entries_by_merchant_id_data_kind( &self, - _merchant_id: &str, - _data_kind: common_enums::BlocklistDataKind, - _limit: i64, - _offset: i64, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, + limit: i64, + offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .list_blocklist_entries_by_merchant_id_data_kind(merchant_id, data_kind, limit, offset) + .await } async fn list_blocklist_entries_by_merchant_id( &self, - _merchant_id: &str, + merchant_id: &str, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .list_blocklist_entries_by_merchant_id(merchant_id) + .await } } diff --git a/crates/router/src/db/blocklist_fingerprint.rs b/crates/router/src/db/blocklist_fingerprint.rs index 9da7c7d8fb2..d9107d3d1c1 100644 --- a/crates/router/src/db/blocklist_fingerprint.rs +++ b/crates/router/src/db/blocklist_fingerprint.rs @@ -80,16 +80,20 @@ impl BlocklistFingerprintInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_fingerprint_entry( &self, - _pm_fingerprint_new: storage::BlocklistFingerprintNew, + pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .insert_blocklist_fingerprint_entry(pm_fingerprint_new) + .await } async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, - _merchant_id: &str, - _fingerprint_id: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .find_blocklist_fingerprint_by_merchant_id_fingerprint_id(merchant_id, fingerprint) + .await } } diff --git a/crates/router/src/db/blocklist_lookup.rs b/crates/router/src/db/blocklist_lookup.rs index 0dfd81c8b8a..f5fb4ea9ed8 100644 --- a/crates/router/src/db/blocklist_lookup.rs +++ b/crates/router/src/db/blocklist_lookup.rs @@ -102,24 +102,30 @@ impl BlocklistLookupInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, - _blocklist_lookup_entry: storage::BlocklistLookupNew, + blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .insert_blocklist_lookup_entry(blocklist_lookup_entry) + .await } async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, - _merchant_id: &str, - _fingerprint: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .find_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) + .await } async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, - _merchant_id: &str, - _fingerprint: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) + .await } } diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 79b38e03f31..174926c7d36 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -119,6 +119,9 @@ Never share your secret api keys. Keep them guarded and secure. crate::routes::gsm::get_gsm_rule, crate::routes::gsm::update_gsm_rule, crate::routes::gsm::delete_gsm_rule, + crate::routes::blocklist::add_entry_to_blocklist, + crate::routes::blocklist::list_blocked_payment_methods, + crate::routes::blocklist::remove_entry_from_blocklist ), components(schemas( crate::types::api::refunds::RefundRequest, @@ -370,7 +373,11 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentLinkResponse, api_models::payments::RetrievePaymentLinkResponse, api_models::payments::PaymentLinkInitiateRequest, - api_models::payments::PaymentLinkStatus + api_models::payments::PaymentLinkStatus, + api_models::blocklist::BlocklistRequest, + api_models::blocklist::BlocklistResponse, + api_models::blocklist::ListBlocklistQuery, + common_enums::enums::BlocklistDataKind )), modifiers(&SecurityAddon) )] diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs index 7c268dddeec..9c93f49ab83 100644 --- a/crates/router/src/routes/blocklist.rs +++ b/crates/router/src/routes/blocklist.rs @@ -8,6 +8,18 @@ use crate::{ services::{api, authentication as auth, authorization::permissions::Permission}, }; +#[utoipa::path( + post, + path = "/blocklist", + request_body = BlocklistRequest, + responses( + (status = 200, description = "Fingerprint Blocked", body = BlocklistResponse), + (status = 400, description = "Invalid Data") + ), + tag = "Blocklist", + operation_id = "Block a Fingerprint", + security(("api_key" = [])) +)] pub async fn add_entry_to_blocklist( state: web::Data<AppState>, req: HttpRequest, @@ -32,6 +44,18 @@ pub async fn add_entry_to_blocklist( .await } +#[utoipa::path( + delete, + path = "/blocklist", + request_body = BlocklistRequest, + responses( + (status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse), + (status = 400, description = "Invalid Data") + ), + tag = "Blocklist", + operation_id = "Unblock a Fingerprint", + security(("api_key" = [])) +)] pub async fn remove_entry_from_blocklist( state: web::Data<AppState>, req: HttpRequest, @@ -56,6 +80,20 @@ pub async fn remove_entry_from_blocklist( .await } +#[utoipa::path( + get, + path = "/blocklist", + params ( + ("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"), + ), + responses( + (status = 200, description = "Blocked Fingerprints", body = BlocklistResponse), + (status = 400, description = "Invalid Data") + ), + tag = "Blocklist", + operation_id = "List Blocked fingerprints of a particular kind", + security(("api_key" = [])) +)] pub async fn list_blocked_payment_methods( state: web::Data<AppState>, req: HttpRequest, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 3e582cfed52..c50f687a181 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -382,6 +382,117 @@ ] } }, + "/blocklist": { + "get": { + "tags": [ + "Blocklist" + ], + "operationId": "List Blocked fingerprints of a particular kind", + "parameters": [ + { + "name": "data_kind", + "in": "query", + "description": "Kind of the fingerprint list requested", + "required": true, + "schema": { + "$ref": "#/components/schemas/BlocklistDataKind" + } + } + ], + "responses": { + "200": { + "description": "Blocked Fingerprints", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "Blocklist" + ], + "operationId": "Block a Fingerprint", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Fingerprint Blocked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "delete": { + "tags": [ + "Blocklist" + ], + "operationId": "Unblock a Fingerprint", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Fingerprint Unblocked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/customers": { "post": { "tags": [ @@ -4035,6 +4146,95 @@ } ] }, + "BlocklistDataKind": { + "type": "string", + "enum": [ + "payment_method", + "card_bin", + "extended_card_bin" + ] + }, + "BlocklistRequest": { + "oneOf": [ + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "card_bin" + ] + }, + "data": { + "type": "string" + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "fingerprint" + ] + }, + "data": { + "type": "string" + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "extended_card_bin" + ] + }, + "data": { + "type": "string" + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "BlocklistResponse": { + "type": "object", + "required": [ + "fingerprint_id", + "data_kind", + "created_at" + ], + "properties": { + "fingerprint_id": { + "type": "string" + }, + "data_kind": { + "$ref": "#/components/schemas/BlocklistDataKind" + }, + "created_at": { + "type": "string", + "format": "date-time" + } + } + }, "BoletoVoucherData": { "type": "object", "properties": { @@ -6576,6 +6776,27 @@ } } }, + "ListBlocklistQuery": { + "type": "object", + "required": [ + "data_kind" + ], + "properties": { + "data_kind": { + "$ref": "#/components/schemas/BlocklistDataKind" + }, + "limit": { + "type": "integer", + "format": "int32", + "minimum": 0 + }, + "offset": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } + }, "MandateAmountData": { "type": "object", "required": [
2024-01-11T19:39:29Z
## 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 --> This PR adds the api contracts(utoipa) for blocklist 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). --> ## 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 test cases can be found out here in this [PR](https://github.com/juspay/hyperswitch/pull/3056). ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
57f2cff75e58b0a7811492a1fdb636f59dcefbd0
juspay/hyperswitch
juspay__hyperswitch-3432
Bug: feat: Make invite support email array Invite api should support invite of multiple users at a time, instead of single email, it should take an array of emails and sent invitation to each. In case of invitation fails for an email, proper error message should be should be thrown for that email response. Response of multiple invite email will be an array containing email, and the other fields as per success or failure for the response.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 8de6a3c0b4f..056d1b593dc 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -89,6 +89,16 @@ pub struct InviteUserResponse { pub password: Option<Secret<String>>, } +#[derive(Debug, serde::Serialize)] +pub struct InviteMultipleUserResponse { + pub email: pii::Email, + pub is_email_sent: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub password: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option<String>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchMerchantIdRequest { pub merchant_id: String, diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index f4000755b3e..389cb10d7b5 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -56,6 +56,8 @@ pub enum UserErrors { ChangePasswordError, #[error("InvalidDeleteOperation")] InvalidDeleteOperation, + #[error("MaxInvitationsError")] + MaxInvitationsError, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -64,107 +66,118 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon let sub_code = "UR"; match self { Self::InternalServerError => { - AER::InternalServerError(ApiError::new("HE", 0, "Something Went Wrong", None)) + AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None)) + } + Self::InvalidCredentials => { + AER::Unauthorized(ApiError::new(sub_code, 1, self.get_error_message(), None)) + } + Self::UserNotFound => { + AER::Unauthorized(ApiError::new(sub_code, 2, self.get_error_message(), None)) + } + Self::UserExists => { + AER::BadRequest(ApiError::new(sub_code, 3, self.get_error_message(), None)) } - Self::InvalidCredentials => AER::Unauthorized(ApiError::new( - sub_code, - 1, - "Incorrect email or password", - None, - )), - Self::UserNotFound => AER::Unauthorized(ApiError::new( - sub_code, - 2, - "Email doesn’t exist. Register", - None, - )), - Self::UserExists => AER::BadRequest(ApiError::new( - sub_code, - 3, - "An account already exists with this email", - None, - )), Self::LinkInvalid => { - AER::Unauthorized(ApiError::new(sub_code, 4, "Invalid or expired link", None)) + AER::Unauthorized(ApiError::new(sub_code, 4, self.get_error_message(), None)) + } + Self::UnverifiedUser => { + AER::Unauthorized(ApiError::new(sub_code, 5, self.get_error_message(), None)) + } + Self::InvalidOldPassword => { + AER::BadRequest(ApiError::new(sub_code, 6, self.get_error_message(), None)) } - Self::UnverifiedUser => AER::Unauthorized(ApiError::new( - sub_code, - 5, - "Kindly verify your account", - None, - )), - Self::InvalidOldPassword => AER::BadRequest(ApiError::new( - sub_code, - 6, - "Old password incorrect. Please enter the correct password", - None, - )), Self::EmailParsingError => { - AER::BadRequest(ApiError::new(sub_code, 7, "Invalid Email", None)) + AER::BadRequest(ApiError::new(sub_code, 7, self.get_error_message(), None)) } Self::NameParsingError => { - AER::BadRequest(ApiError::new(sub_code, 8, "Invalid Name", None)) + AER::BadRequest(ApiError::new(sub_code, 8, self.get_error_message(), None)) } Self::PasswordParsingError => { - AER::BadRequest(ApiError::new(sub_code, 9, "Invalid Password", None)) + AER::BadRequest(ApiError::new(sub_code, 9, self.get_error_message(), None)) } Self::UserAlreadyVerified => { - AER::Unauthorized(ApiError::new(sub_code, 11, "User already verified", None)) + AER::Unauthorized(ApiError::new(sub_code, 11, self.get_error_message(), None)) } Self::CompanyNameParsingError => { - AER::BadRequest(ApiError::new(sub_code, 14, "Invalid Company Name", None)) + AER::BadRequest(ApiError::new(sub_code, 14, self.get_error_message(), None)) } Self::MerchantAccountCreationError(error_message) => { AER::InternalServerError(ApiError::new(sub_code, 15, error_message, None)) } Self::InvalidEmailError => { - AER::BadRequest(ApiError::new(sub_code, 16, "Invalid Email", None)) + AER::BadRequest(ApiError::new(sub_code, 16, self.get_error_message(), None)) } Self::MerchantIdNotFound => { - AER::BadRequest(ApiError::new(sub_code, 18, "Invalid Merchant ID", None)) + AER::BadRequest(ApiError::new(sub_code, 18, self.get_error_message(), None)) } Self::MetadataAlreadySet => { - AER::BadRequest(ApiError::new(sub_code, 19, "Metadata already set", None)) + AER::BadRequest(ApiError::new(sub_code, 19, self.get_error_message(), None)) } Self::DuplicateOrganizationId => AER::InternalServerError(ApiError::new( sub_code, 21, - "An Organization with the id already exists", + self.get_error_message(), None, )), Self::InvalidRoleId => { - AER::BadRequest(ApiError::new(sub_code, 22, "Invalid Role ID", None)) + AER::BadRequest(ApiError::new(sub_code, 22, self.get_error_message(), None)) } - Self::InvalidRoleOperation => AER::BadRequest(ApiError::new( - sub_code, - 23, - "User Role Operation Not Supported", - None, - )), - Self::IpAddressParsingFailed => { - AER::InternalServerError(ApiError::new(sub_code, 24, "Something Went Wrong", None)) + Self::InvalidRoleOperation => { + AER::BadRequest(ApiError::new(sub_code, 23, self.get_error_message(), None)) } - Self::InvalidMetadataRequest => AER::BadRequest(ApiError::new( + Self::IpAddressParsingFailed => AER::InternalServerError(ApiError::new( sub_code, - 26, - "Invalid Metadata Request", + 24, + self.get_error_message(), None, )), + Self::InvalidMetadataRequest => { + AER::BadRequest(ApiError::new(sub_code, 26, self.get_error_message(), None)) + } Self::MerchantIdParsingError => { - AER::BadRequest(ApiError::new(sub_code, 28, "Invalid Merchant Id", None)) + AER::BadRequest(ApiError::new(sub_code, 28, self.get_error_message(), None)) } - Self::ChangePasswordError => AER::BadRequest(ApiError::new( - sub_code, - 29, - "Old and new password cannot be same", - None, - )), - Self::InvalidDeleteOperation => AER::BadRequest(ApiError::new( - sub_code, - 30, - "Delete Operation Not Supported", - None, - )), + Self::ChangePasswordError => { + AER::BadRequest(ApiError::new(sub_code, 29, self.get_error_message(), None)) + } + Self::InvalidDeleteOperation => { + AER::BadRequest(ApiError::new(sub_code, 30, self.get_error_message(), None)) + } + Self::MaxInvitationsError => { + AER::BadRequest(ApiError::new(sub_code, 31, self.get_error_message(), None)) + } + } + } +} + +impl UserErrors { + pub fn get_error_message(&self) -> &str { + match self { + Self::InternalServerError => "Something went wrong", + Self::InvalidCredentials => "Incorrect email or password", + Self::UserNotFound => "Email doesn’t exist. Register", + Self::UserExists => "An account already exists with this email", + Self::LinkInvalid => "Invalid or expired link", + Self::UnverifiedUser => "Kindly verify your account", + Self::InvalidOldPassword => "Old password incorrect. Please enter the correct password", + Self::EmailParsingError => "Invalid Email", + Self::NameParsingError => "Invalid Name", + Self::PasswordParsingError => "Invalid Password", + Self::UserAlreadyVerified => "User already verified", + Self::CompanyNameParsingError => "Invalid Company Name", + Self::MerchantAccountCreationError(error_message) => error_message, + Self::InvalidEmailError => "Invalid Email", + Self::MerchantIdNotFound => "Invalid Merchant ID", + Self::MetadataAlreadySet => "Metadata already set", + Self::DuplicateOrganizationId => "An Organization with the id already exists", + Self::InvalidRoleId => "Invalid Role ID", + Self::InvalidRoleOperation => "User Role Operation Not Supported", + Self::IpAddressParsingFailed => "Something went wrong", + Self::InvalidMetadataRequest => "Invalid Metadata Request", + Self::MerchantIdParsingError => "Invalid Merchant Id", + Self::ChangePasswordError => "Old and new password cannot be the same", + Self::InvalidDeleteOperation => "Delete Operation Not Supported", + Self::MaxInvitationsError => "Maximum invite count per request exceeded", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 3384e229009..c2ed78f8665 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,4 +1,4 @@ -use api_models::user as user_api; +use api_models::user::{self as user_api, InviteMultipleUserResponse}; use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew}; #[cfg(feature = "email")] use error_stack::IntoReport; @@ -9,7 +9,7 @@ use router_env::env; #[cfg(feature = "email")] use router_env::logger; -use super::errors::{UserErrors, UserResponse}; +use super::errors::{UserErrors, UserResponse, UserResult}; #[cfg(feature = "email")] use crate::services::email::types as email_types; use crate::{ @@ -407,6 +407,12 @@ pub async fn invite_user( .await .change_context(UserErrors::InternalServerError)?; + let invitation_status = if cfg!(feature = "email") { + UserStatus::InvitationSent + } else { + UserStatus::Active + }; + let now = common_utils::date_time::now(); state .store @@ -415,7 +421,7 @@ pub async fn invite_user( merchant_id: user_from_token.merchant_id, role_id: request.role_id, org_id: user_from_token.org_id, - status: UserStatus::InvitationSent, + status: invitation_status, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id, created_at: now, @@ -467,6 +473,181 @@ pub async fn invite_user( } } +pub async fn invite_multiple_user( + state: AppState, + user_from_token: auth::UserFromToken, + requests: Vec<user_api::InviteUserRequest>, +) -> UserResponse<Vec<InviteMultipleUserResponse>> { + if requests.len() > 10 { + return Err(UserErrors::MaxInvitationsError.into()) + .attach_printable("Number of invite requests must not exceed 10"); + } + + let responses = futures::future::join_all(requests.iter().map(|request| async { + match handle_invitation(&state, &user_from_token, request).await { + Ok(response) => response, + Err(error) => InviteMultipleUserResponse { + email: request.email.clone(), + is_email_sent: false, + password: None, + error: Some(error.current_context().get_error_message().to_string()), + }, + } + })) + .await; + + Ok(ApplicationResponse::Json(responses)) +} + +async fn handle_invitation( + state: &AppState, + user_from_token: &auth::UserFromToken, + request: &user_api::InviteUserRequest, +) -> UserResult<InviteMultipleUserResponse> { + let inviter_user = user_from_token.get_user(state.clone()).await?; + + if inviter_user.email == request.email { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("User Inviting themself"); + } + + utils::user_role::validate_role_id(request.role_id.as_str())?; + let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; + let invitee_user = state + .store + .find_user_by_email(invitee_email.clone().get_secret().expose().as_str()) + .await; + + if let Ok(invitee_user) = invitee_user { + handle_existing_user_invitation(state, user_from_token, request, invitee_user.into()).await + } else if invitee_user + .as_ref() + .map_err(|e| e.current_context().is_db_not_found()) + .err() + .unwrap_or(false) + { + handle_new_user_invitation(state, user_from_token, request).await + } else { + Err(UserErrors::InternalServerError.into()) + } +} + +//TODO: send email +async fn handle_existing_user_invitation( + state: &AppState, + user_from_token: &auth::UserFromToken, + request: &user_api::InviteUserRequest, + invitee_user_from_db: domain::UserFromStorage, +) -> UserResult<InviteMultipleUserResponse> { + let now = common_utils::date_time::now(); + state + .store + .insert_user_role(UserRoleNew { + user_id: invitee_user_from_db.get_user_id().to_owned(), + merchant_id: user_from_token.merchant_id.clone(), + role_id: request.role_id.clone(), + org_id: user_from_token.org_id.clone(), + status: UserStatus::Active, + created_by: user_from_token.user_id.clone(), + last_modified_by: user_from_token.user_id.clone(), + created_at: now, + last_modified: now, + }) + .await + .map_err(|e| { + if e.current_context().is_db_unique_violation() { + e.change_context(UserErrors::UserExists) + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + + Ok(InviteMultipleUserResponse { + email: request.email.clone(), + is_email_sent: false, + password: None, + error: None, + }) +} + +async fn handle_new_user_invitation( + state: &AppState, + user_from_token: &auth::UserFromToken, + request: &user_api::InviteUserRequest, +) -> UserResult<InviteMultipleUserResponse> { + let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?; + + new_user + .insert_user_in_db(state.store.as_ref()) + .await + .change_context(UserErrors::InternalServerError)?; + + let invitation_status = if cfg!(feature = "email") { + UserStatus::InvitationSent + } else { + UserStatus::Active + }; + + let now = common_utils::date_time::now(); + state + .store + .insert_user_role(UserRoleNew { + user_id: new_user.get_user_id().to_owned(), + merchant_id: user_from_token.merchant_id.clone(), + role_id: request.role_id.clone(), + org_id: user_from_token.org_id.clone(), + status: invitation_status, + created_by: user_from_token.user_id.clone(), + last_modified_by: user_from_token.user_id.clone(), + created_at: now, + last_modified: now, + }) + .await + .map_err(|e| { + if e.current_context().is_db_unique_violation() { + e.change_context(UserErrors::UserExists) + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + + let is_email_sent; + #[cfg(feature = "email")] + { + let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; + let email_contents = email_types::InviteUser { + recipient_email: invitee_email, + user_name: domain::UserName::new(new_user.get_name())?, + settings: state.conf.clone(), + subject: "You have been invited to join Hyperswitch Community!", + }; + let send_email_result = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await; + logger::info!(?send_email_result); + is_email_sent = send_email_result.is_ok(); + } + #[cfg(not(feature = "email"))] + { + is_email_sent = false; + } + + Ok(InviteMultipleUserResponse { + is_email_sent, + password: if cfg!(not(feature = "email")) { + Some(new_user.get_password().get_secret()) + } else { + None + }, + email: request.email.clone(), + error: None, + }) +} + pub async fn create_internal_user( state: AppState, request: user_api::CreateInternalUserRequest, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 71c79295c73..44822efddc4 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -970,6 +970,9 @@ impl User { .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service(web::resource("/user/invite/accept").route(web::post().to(accept_invitation))) .service(web::resource("/update").route(web::post().to(update_user_account_details))) + .service( + web::resource("/user/invite_multiple").route(web::post().to(invite_multiple_user)), + ) .service( web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 30348513c2b..6df8c7fb7a7 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -176,6 +176,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ForgotPassword | Flow::ResetPassword | Flow::InviteUser + | Flow::InviteMultipleUser | Flow::DeleteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmail diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index eca32318adf..02704cf701f 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -350,6 +350,23 @@ pub async fn invite_user( )) .await } +pub async fn invite_multiple_user( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<Vec<user_api::InviteUserRequest>>, +) -> HttpResponse { + let flow = Flow::InviteMultipleUser; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload.into_inner(), + user_core::invite_multiple_user, + &auth::JWTAuth(Permission::UsersWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} #[cfg(feature = "email")] pub async fn verify_email( diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 84f2e3e1267..998c52f2c13 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -321,6 +321,8 @@ pub enum Flow { ResetPassword, /// Invite users InviteUser, + /// Invite multiple users + InviteMultipleUser, /// Delete user DeleteUser, /// Incremental Authorization flow
2024-01-22T23:16:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The endpoint `/invite_multiple`, gives support to invite more than one user at a time. ### 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 Currently we can only invite one user at a time. ## How did you test it? Curl for invite_multiple: ``` curl --location 'http://localhost:8080/user/user/invite_multiple' \ --header 'Authorization: Bearer JWT' \ --data-raw '[ { "email": "admin7@juspay.in", "name": "25", "role_id": "merchant_view_only" }, { "email": "test2@juspay.in", "name": "25", "role_id": "merchant_view_only" }, { "email": "12345@juspay.n", "name": "25", "role_id": "merchant_view_only" } ]' ``` <img width="1263" alt="Screenshot 2024-01-23 at 4 28 32 AM" src="https://github.com/juspay/hyperswitch/assets/64925866/217cbc2d-a065-4be9-8f04-f3121b017a34"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d827c9af29b8516f379e648e00f4ab307ae1a34d
juspay/hyperswitch
juspay__hyperswitch-3433
Bug: [FEATURE] Update card_details for an existing mandate ### Feature Description There is an existing mandate, with current card details and the Customer for some reason wants to update his card details for that particular mandate. ### Possible Implementation The possible implementation for this would is, - while making a `/payments` call create the `Mandate_data` object with an `update_existing_mandate` field which would have the `current/existing mandate`. - if in the request we get the `update_existing_mandate` as some valid mandate for that particular merchant, we create a new Mandate on the connector's end and if that creation is a success, we revoke the Previous Mandate with the Previous Card Details on the connectors end - And then we'll map the `new_connector_mandate_id` with our existing `mandate_id` and update the following in the db - Create a new list that contains the `old_connector_mandate_id' for keeping a reference of older mandates that were revoked or need to be revoked ### TBDs - [ ] What do we do when there’s no revoke call supported by connector? > We add the task in process tracker - [ ] What if the revoke retries call fails even after adding the task to the process tracker? - [ ] How do we deal if there's a Connector Error while creating a mandate? - [ ] https://github.com/juspay/hyperswitch/issues/3465 - [ ] https://github.com/juspay/hyperswitch/pull/3452 - [ ] https://github.com/juspay/hyperswitch/issues/3464 - [ ] https://github.com/juspay/hyperswitch/issues/3538 ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 57c66dc5a7b..8c27f498d7a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -617,10 +617,18 @@ pub enum MandateReferenceId { NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns } -#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, + pub update_history: Option<Vec<UpdateHistory>>, +} + +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] +pub struct UpdateHistory { + pub connector_mandate_id: Option<String>, + pub payment_method_id: String, + pub original_payment_id: Option<String>, } impl MandateIds { @@ -637,6 +645,8 @@ impl MandateIds { #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { + /// A way to update the mandate's payment method details + pub update_mandate_id: Option<String>, /// A concent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used diff --git a/crates/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs index afdcda3a40e..319a78cf661 100644 --- a/crates/data_models/src/mandates.rs +++ b/crates/data_models/src/mandates.rs @@ -9,6 +9,13 @@ use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use time::PrimitiveDateTime; +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct MandateDetails { + pub update_mandate_id: Option<String>, + pub mandate_type: Option<MandateDataType>, +} + #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { @@ -16,6 +23,13 @@ pub enum MandateDataType { MultiUse(Option<MandateAmountData>), } +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +#[serde(untagged)] +pub enum MandateTypeDetails { + MandateType(MandateDataType), + MandateDetails(MandateDetails), +} #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: i64, @@ -29,6 +43,8 @@ pub struct MandateAmountData { // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, Clone)] pub struct MandateData { + /// A way to update the mandate's payment method details + pub update_mandate_id: Option<String>, /// A concent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used @@ -90,6 +106,7 @@ impl From<ApiMandateData> for MandateData { Self { customer_acceptance: value.customer_acceptance.map(|d| d.into()), mandate_type: value.mandate_type.map(|d| d.into()), + update_mandate_id: value.update_mandate_id, } } } diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs index 3e6ba9e37f8..e6b9950b459 100644 --- a/crates/data_models/src/payments/payment_attempt.rs +++ b/crates/data_models/src/payments/payment_attempt.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use super::PaymentIntent; -use crate::{errors, mandates::MandateDataType, ForeignIDRef}; +use crate::{errors, mandates::MandateTypeDetails, ForeignIDRef}; #[async_trait::async_trait] pub trait PaymentAttemptInterface { @@ -143,7 +143,7 @@ pub struct PaymentAttempt { pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction - pub mandate_details: Option<MandateDataType>, + pub mandate_details: Option<MandateTypeDetails>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side @@ -184,7 +184,7 @@ pub struct PaymentAttemptNew { pub attempt_id: String, pub status: storage_enums::AttemptStatus, pub amount: i64, - /// amount + surcharge_amount + tax_amount + /// amount + surcharge_amount + tax_amount /// This field will always be derived before updating in the Database pub net_amount: i64, pub currency: Option<storage_enums::Currency>, @@ -221,7 +221,7 @@ pub struct PaymentAttemptNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<MandateDataType>, + pub mandate_details: Option<MandateTypeDetails>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index a06937c99a6..babffdbc4a8 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -166,6 +166,17 @@ use diesel::{ expression::AsExpression, sql_types::Jsonb, }; + +#[derive( + serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, +)] +#[diesel(sql_type = Jsonb)] +#[serde(rename_all = "snake_case")] +pub struct MandateDetails { + pub update_mandate_id: Option<String>, + pub mandate_type: Option<MandateDataType>, +} + #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] @@ -185,6 +196,7 @@ where Ok(serde_json::from_value(value)?) } } + impl ToSql<Jsonb, diesel::pg::Pg> for MandateDataType where serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, @@ -199,6 +211,40 @@ where } } +#[derive( + serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, +)] +#[diesel(sql_type = Jsonb)] +#[serde(untagged)] +#[serde(rename_all = "snake_case")] +pub enum MandateTypeDetails { + MandateType(MandateDataType), + MandateDetails(MandateDetails), +} + +impl<DB: Backend> FromSql<Jsonb, DB> for MandateTypeDetails +where + serde_json::Value: FromSql<Jsonb, DB>, +{ + fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { + let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?; + Ok(serde_json::from_value(value)?) + } +} +impl ToSql<Jsonb, diesel::pg::Pg> for MandateTypeDetails +where + serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result { + let value = serde_json::to_value(self)?; + + // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends + // please refer to the diesel migration blog: + // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations + <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) + } +} + #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: i64, diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs index cc3474914c0..31c6ef62f2b 100644 --- a/crates/diesel_models/src/mandate.rs +++ b/crates/diesel_models/src/mandate.rs @@ -75,6 +75,12 @@ pub enum MandateUpdate { ConnectorReferenceUpdate { connector_mandate_ids: Option<pii::SecretSerdeValue>, }, + ConnectorMandateIdUpdate { + connector_mandate_id: Option<String>, + connector_mandate_ids: Option<pii::SecretSerdeValue>, + payment_method_id: String, + original_payment_id: Option<String>, + }, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] @@ -89,6 +95,9 @@ pub struct MandateUpdateInternal { mandate_status: Option<storage_enums::MandateStatus>, amount_captured: Option<i64>, connector_mandate_ids: Option<pii::SecretSerdeValue>, + connector_mandate_id: Option<String>, + payment_method_id: Option<String>, + original_payment_id: Option<String>, } impl From<MandateUpdate> for MandateUpdateInternal { @@ -98,16 +107,34 @@ impl From<MandateUpdate> for MandateUpdateInternal { mandate_status: Some(mandate_status), connector_mandate_ids: None, amount_captured: None, + connector_mandate_id: None, + payment_method_id: None, + original_payment_id: None, }, MandateUpdate::CaptureAmountUpdate { amount_captured } => Self { mandate_status: None, amount_captured, connector_mandate_ids: None, + connector_mandate_id: None, + payment_method_id: None, + original_payment_id: None, }, MandateUpdate::ConnectorReferenceUpdate { - connector_mandate_ids: connector_mandate_id, + connector_mandate_ids, + } => Self { + connector_mandate_ids, + ..Default::default() + }, + MandateUpdate::ConnectorMandateIdUpdate { + connector_mandate_id, + connector_mandate_ids, + payment_method_id, + original_payment_id, } => Self { - connector_mandate_ids: connector_mandate_id, + connector_mandate_id, + connector_mandate_ids, + payment_method_id: Some(payment_method_id), + original_payment_id, ..Default::default() }, } diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index d08c146b0b8..4a7603384c5 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -51,7 +51,7 @@ pub struct PaymentAttempt { pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction - pub mandate_details: Option<storage_enums::MandateDataType>, + pub mandate_details: Option<storage_enums::MandateTypeDetails>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side @@ -126,7 +126,7 @@ pub struct PaymentAttemptNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<storage_enums::MandateDataType>, + pub mandate_details: Option<storage_enums::MandateTypeDetails>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 5a1ea696c56..5a2226f0676 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -5,7 +5,7 @@ use common_enums::{ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums::MandateDataType, schema::payment_attempt, PaymentAttemptNew}; +use crate::{enums::MandateTypeDetails, schema::payment_attempt, PaymentAttemptNew}; #[derive( Clone, Debug, Default, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, @@ -50,7 +50,7 @@ pub struct PaymentAttemptBatchNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<MandateDataType>, + pub mandate_details: Option<MandateTypeDetails>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub connector_transaction_id: Option<String>, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 810e0ed1d28..aac150b5079 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -753,6 +753,7 @@ impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments:: user_agent: online.user_agent, }), }), + update_mandate_id: None, }); Ok(mandate_data) } diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index b6837d14f82..7299ef624d8 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -1,13 +1,13 @@ +pub mod helpers; pub mod utils; - use api_models::payments; use common_utils::{ext_traits::Encode, pii}; -use diesel_models::enums as storage_enums; +use diesel_models::{enums as storage_enums, Mandate}; use error_stack::{report, IntoReport, ResultExt}; use futures::future; use router_env::{instrument, logger, tracing}; -use super::payments::helpers; +use super::payments::helpers as payment_helper; use crate::{ core::{ errors::{self, RouterResponse, StorageErrorExt}, @@ -64,34 +64,17 @@ pub async fn revoke_mandate( common_enums::MandateStatus::Active | common_enums::MandateStatus::Inactive | common_enums::MandateStatus::Pending => { - let profile_id = if let Some(ref payment_id) = mandate.original_payment_id { - let pi = db - .find_payment_intent_by_payment_id_merchant_id( - payment_id, - &merchant_account.merchant_id, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::PaymentNotFound)?; - let profile_id = pi.profile_id.clone().ok_or( - errors::ApiErrorResponse::BusinessProfileNotFound { - id: pi - .profile_id - .unwrap_or_else(|| "Profile id is Null".to_string()), - }, - )?; - Ok(profile_id) - } else { - Err(errors::ApiErrorResponse::PaymentNotFound) - }?; + let profile_id = + helpers::get_profile_id_for_mandate(&state, &merchant_account, mandate.clone()) + .await?; - let merchant_connector_account = helpers::get_merchant_connector_account( + let merchant_connector_account = payment_helper::get_merchant_connector_account( &state, &merchant_account.merchant_id, None, &key_store, &profile_id, - &mandate.connector, + &mandate.connector.clone(), mandate.merchant_connector_id.as_ref(), ) .await?; @@ -243,7 +226,72 @@ where _ => Some(router_data.request.get_payment_method_data()), } } +pub async fn update_mandate_procedure<F, FData>( + state: &AppState, + resp: types::RouterData<F, FData, types::PaymentsResponseData>, + mandate: Mandate, + merchant_id: &str, + pm_id: Option<String>, +) -> errors::RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> +where + FData: MandateBehaviour, +{ + let mandate_details = match &resp.response { + Ok(types::PaymentsResponseData::TransactionResponse { + mandate_reference, .. + }) => mandate_reference, + Ok(_) => Err(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Unexpected response received")?, + Err(_) => return Ok(resp), + }; + let old_record = payments::UpdateHistory { + connector_mandate_id: mandate.connector_mandate_id, + payment_method_id: mandate.payment_method_id, + original_payment_id: mandate.original_payment_id, + }; + + let mandate_ref = mandate + .connector_mandate_ids + .parse_value::<payments::ConnectorMandateReferenceId>("Connector Reference Id") + .change_context(errors::ApiErrorResponse::MandateDeserializationFailed)?; + + let mut update_history = mandate_ref.update_history.unwrap_or_default(); + update_history.push(old_record); + + let updated_mandate_ref = payments::ConnectorMandateReferenceId { + connector_mandate_id: mandate_details + .as_ref() + .and_then(|mandate_ref| mandate_ref.connector_mandate_id.clone()), + payment_method_id: pm_id.clone(), + update_history: Some(update_history), + }; + + let connector_mandate_ids = + Encode::<types::MandateReference>::encode_to_value(&updated_mandate_ref) + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(masking::Secret::new)?; + + let _update_mandate_details = state + .store + .update_mandate_by_merchant_id_mandate_id( + merchant_id, + &mandate.mandate_id, + diesel_models::MandateUpdate::ConnectorMandateIdUpdate { + connector_mandate_id: mandate_details + .as_ref() + .and_then(|man_ref| man_ref.connector_mandate_id.clone()), + connector_mandate_ids: Some(connector_mandate_ids), + payment_method_id: pm_id + .unwrap_or("Error retrieving the payment_method_id".to_string()), + original_payment_id: Some(resp.payment_id.clone()), + }, + ) + .await + .change_context(errors::ApiErrorResponse::MandateUpdateFailed)?; + Ok(resp) +} pub async fn mandate_procedure<F, FData>( state: &AppState, mut resp: types::RouterData<F, FData, types::PaymentsResponseData>, @@ -324,7 +372,7 @@ where }) .transpose()?; - if let Some(new_mandate_data) = helpers::generate_mandate( + if let Some(new_mandate_data) = payment_helper::generate_mandate( resp.merchant_id.clone(), resp.payment_id.clone(), resp.connector.clone(), @@ -363,6 +411,8 @@ where api_models::payments::ConnectorMandateReferenceId { connector_mandate_id: connector_id.connector_mandate_id, payment_method_id: connector_id.payment_method_id, + update_history:None, + } ))) })); diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs new file mode 100644 index 00000000000..150130ed9e5 --- /dev/null +++ b/crates/router/src/core/mandate/helpers.rs @@ -0,0 +1,35 @@ +use common_utils::errors::CustomResult; +use diesel_models::Mandate; +use error_stack::ResultExt; + +use crate::{core::errors, routes::AppState, types::domain}; + +pub async fn get_profile_id_for_mandate( + state: &AppState, + merchant_account: &domain::MerchantAccount, + mandate: Mandate, +) -> CustomResult<String, errors::ApiErrorResponse> { + let profile_id = if let Some(ref payment_id) = mandate.original_payment_id { + let pi = state + .store + .find_payment_intent_by_payment_id_merchant_id( + payment_id, + &merchant_account.merchant_id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + let profile_id = + pi.profile_id + .clone() + .ok_or(errors::ApiErrorResponse::BusinessProfileNotFound { + id: pi + .profile_id + .unwrap_or_else(|| "Profile id is Null".to_string()), + })?; + Ok(profile_id) + } else { + Err(errors::ApiErrorResponse::PaymentNotFound) + }?; + Ok(profile_id) +} diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 3dbd6fcb215..e08dbc61f5e 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1823,14 +1823,24 @@ pub async fn list_payment_methods( } else { api_surcharge_decision_configs::MerchantSurchargeConfigs::default() }; + print!("PAMT{:?}", payment_attempt); Ok(services::ApplicationResponse::Json( api::PaymentMethodListResponse { redirect_url: merchant_account.return_url, merchant_name: merchant_account.merchant_name, payment_type, payment_methods: payment_method_responses, - mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map( - |d| match d { + mandate_payment: payment_attempt + .and_then(|inner| inner.mandate_details) + .and_then(|man_type_details| match man_type_details { + data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => { + Some(mandate_type) + } + data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => { + mandate_details.mandate_type + } + }) + .map(|d| match d { data_models::mandates::MandateDataType::SingleUse(i) => { api::MandateType::SingleUse(api::MandateAmountData { amount: i.amount, @@ -1852,8 +1862,7 @@ pub async fn list_payment_methods( data_models::mandates::MandateDataType::MultiUse(None) => { api::MandateType::MultiUse(None) } - }, - ), + }), show_surcharge_breakup_screen: merchant_surcharge_configs .show_surcharge_breakup_screen .unwrap_or_default(), diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index d6343ed871b..8b0b54158fd 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -1,9 +1,10 @@ use async_trait::async_trait; +use error_stack::{IntoReport, ResultExt}; use super::{ConstructFlowSpecificData, Feature}; use crate::{ core::{ - errors::{self, ConnectorErrorExt, RouterResult}, + errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, @@ -65,16 +66,16 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup types::SetupMandateRequestData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); + let resp = services::execute_connector_processing_step( state, connector_integration, &self, - call_connector_action, + call_connector_action.clone(), connector_request, ) .await .to_setup_mandate_failed_response()?; - let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -86,14 +87,84 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup )) .await?; - mandate::mandate_procedure( - state, - resp, - maybe_customer, - pm_id, - connector.merchant_connector_id.clone(), - ) - .await + if let Some(mandate_id) = self + .request + .setup_mandate_details + .as_ref() + .and_then(|mandate_data| mandate_data.update_mandate_id.clone()) + { + let mandate = state + .store + .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &mandate_id) + .await + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + + let profile_id = mandate::helpers::get_profile_id_for_mandate( + state, + merchant_account, + mandate.clone(), + ) + .await?; + match resp.response { + Ok(types::PaymentsResponseData::TransactionResponse { .. }) => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + types::api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > = connector.connector.get_connector_integration(); + let merchant_connector_account = helpers::get_merchant_connector_account( + state, + &merchant_account.merchant_id, + None, + key_store, + &profile_id, + &mandate.connector, + mandate.merchant_connector_id.as_ref(), + ) + .await?; + + let router_data = mandate::utils::construct_mandate_revoke_router_data( + merchant_connector_account, + merchant_account, + mandate.clone(), + ) + .await?; + + let _response = services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + call_connector_action, + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + // TODO:Add the revoke mandate task to process tracker + mandate::update_mandate_procedure( + state, + resp, + mandate, + &merchant_account.merchant_id, + pm_id, + ) + .await + } + Ok(_) => Err(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Unexpected response received")?, + Err(_) => Ok(resp), + } + } else { + mandate::mandate_procedure( + state, + resp, + maybe_customer, + pm_id, + connector.merchant_connector_id.clone(), + ) + .await + } } async fn add_access_token<'a>( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 0cbed255348..520582eb22f 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -840,7 +840,7 @@ fn validate_new_mandate_request( let mandate_details = match mandate_data.mandate_type { Some(api_models::payments::MandateType::SingleUse(details)) => Some(details), Some(api_models::payments::MandateType::MultiUse(details)) => details, - None => None, + _ => None, }; mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)| utils::when (start_date >= end_date, || { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index c81145c5de7..14fc28d6723 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -431,7 +431,29 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt setup_mandate = setup_mandate.map(|mut sm| { - sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type); + sm.mandate_type = payment_attempt + .mandate_details + .clone() + .and_then(|mandate| match mandate { + data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => { + Some(mandate_type) + } + data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => { + mandate_details.mandate_type + } + }) + .or(sm.mandate_type); + sm.update_mandate_id = payment_attempt + .mandate_details + .clone() + .and_then(|mandate| match mandate { + data_models::mandates::MandateTypeDetails::MandateType(_) => None, + data_models::mandates::MandateTypeDetails::MandateDetails(update_id) => { + Some(update_id.update_mandate_id) + } + }) + .flatten() + .or(sm.update_mandate_id); sm }); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 2b25a74deb1..d02ad15fbd6 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -3,7 +3,10 @@ use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; -use data_models::{mandates::MandateData, payments::payment_attempt::PaymentAttempt}; +use data_models::{ + mandates::{MandateData, MandateDetails, MandateTypeDetails}, + payments::payment_attempt::PaymentAttempt, +}; use diesel_models::ephemeral_key; use error_stack::{self, ResultExt}; use masking::PeekInterface; @@ -255,7 +258,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; - + // connector mandate reference update history let mandate_id = request .mandate_id .as_ref() @@ -284,10 +287,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> api_models::payments::MandateIds { mandate_id: mandate_obj.mandate_id, mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - api_models::payments::ConnectorMandateReferenceId { - connector_mandate_id: connector_id.connector_mandate_id, - payment_method_id: connector_id.payment_method_id, - }, + api_models::payments::ConnectorMandateReferenceId{ + connector_mandate_id: connector_id.connector_mandate_id, + payment_method_id: connector_id.payment_method_id, + update_history: None + } )) } }), @@ -701,6 +705,35 @@ impl PaymentCreate { .surcharge_details .and_then(|surcharge_details| surcharge_details.tax_amount); + if request.mandate_data.as_ref().map_or(false, |mandate_data| { + mandate_data.update_mandate_id.is_some() && mandate_data.mandate_type.is_some() + }) { + Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})? + } + + let mandate_dets = if let Some(update_id) = request + .mandate_data + .as_ref() + .and_then(|inner| inner.update_mandate_id.clone()) + { + let mandate_data = MandateDetails { + update_mandate_id: Some(update_id), + mandate_type: None, + }; + Some(MandateTypeDetails::MandateDetails(mandate_data)) + } else { + // let mandate_type: data_models::mandates::MandateDataType = + + let mandate_data = MandateDetails { + update_mandate_id: None, + mandate_type: request + .mandate_data + .as_ref() + .and_then(|inner| inner.mandate_type.clone().map(Into::into)), + }; + Some(MandateTypeDetails::MandateDetails(mandate_data)) + }; + Ok(( storage::PaymentAttemptNew { payment_id: payment_id.to_string(), @@ -727,10 +760,7 @@ impl PaymentCreate { business_sub_label: request.business_sub_label.clone(), surcharge_amount, tax_amount, - mandate_details: request - .mandate_data - .as_ref() - .and_then(|inner| inner.mandate_type.clone().map(Into::into)), + mandate_details: mandate_dets, ..storage::PaymentAttemptNew::default() }, additional_pm_data, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index e002b92d181..015ef5cea6e 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -255,10 +255,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> api_models::payments::MandateIds { mandate_id: mandate_obj.mandate_id, mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - api_models::payments::ConnectorMandateReferenceId { - connector_mandate_id: connector_id.connector_mandate_id, - payment_method_id: connector_id.payment_method_id, - }, + api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None }, )) } }), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5f0c702a29d..61917fdcd2e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -636,6 +636,7 @@ where api::MandateType::MultiUse(None) } }), + update_mandate_id: d.update_mandate_id, }), auth_flow == services::AuthFlow::Merchant, ) diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index fcd71719657..0cf5cabf2e4 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -202,6 +202,18 @@ impl MandateInterface for MockDb { } => { mandate.connector_mandate_ids = connector_mandate_ids; } + + diesel_models::MandateUpdate::ConnectorMandateIdUpdate { + connector_mandate_id, + connector_mandate_ids, + payment_method_id, + original_payment_id, + } => { + mandate.connector_mandate_ids = connector_mandate_ids; + mandate.connector_mandate_id = connector_mandate_id; + mandate.payment_method_id = payment_method_id; + mandate.original_payment_id = original_payment_id + } } Ok(mandate.clone()) } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 307dff55071..bc8ab2e05e7 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1674,7 +1674,7 @@ pub fn build_redirection_form( // Initialize the ThreeDSService const threeDS = gateway.get3DSecure(); - + const options = {{ customerVaultId: '{customer_vault_id}', currency: '{currency}', diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 786a8c55182..41aefc9026d 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -323,6 +323,7 @@ impl ForeignFrom<api_models::payments::MandateData> for data_models::mandates::M data_models::mandates::MandateDataType::MultiUse(None) } }), + update_mandate_id: d.update_mandate_id, } } } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index f8f752c6bc8..b8d71cb32b7 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -2,7 +2,7 @@ use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMet use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found}; use data_models::{ errors, - mandates::{MandateAmountData, MandateDataType}, + mandates::{MandateAmountData, MandateDataType, MandateDetails, MandateTypeDetails}, payments::{ payment_attempt::{ PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate, @@ -14,6 +14,7 @@ use data_models::{ use diesel_models::{ enums::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, + MandateDetails as DieselMandateDetails, MandateTypeDetails as DieselMandateTypeOrDetails, MerchantStorageScheme, }, kv, @@ -999,6 +1000,50 @@ impl DataModelExt for MandateAmountData { } } } +impl DataModelExt for MandateDetails { + type StorageModel = DieselMandateDetails; + fn to_storage_model(self) -> Self::StorageModel { + DieselMandateDetails { + update_mandate_id: self.update_mandate_id, + mandate_type: self + .mandate_type + .map(|mand_type| mand_type.to_storage_model()), + } + } + fn from_storage_model(storage_model: Self::StorageModel) -> Self { + Self { + update_mandate_id: storage_model.update_mandate_id, + mandate_type: storage_model + .mandate_type + .map(MandateDataType::from_storage_model), + } + } +} +impl DataModelExt for MandateTypeDetails { + type StorageModel = DieselMandateTypeOrDetails; + + fn to_storage_model(self) -> Self::StorageModel { + match self { + Self::MandateType(mandate_type) => { + DieselMandateTypeOrDetails::MandateType(mandate_type.to_storage_model()) + } + Self::MandateDetails(mandate_details) => { + DieselMandateTypeOrDetails::MandateDetails(mandate_details.to_storage_model()) + } + } + } + + fn from_storage_model(storage_model: Self::StorageModel) -> Self { + match storage_model { + DieselMandateTypeOrDetails::MandateType(data) => { + Self::MandateType(MandateDataType::from_storage_model(data)) + } + DieselMandateTypeOrDetails::MandateDetails(data) => { + Self::MandateDetails(MandateDetails::from_storage_model(data)) + } + } + } +} impl DataModelExt for MandateDataType { type StorageModel = DieselMandateType; @@ -1123,7 +1168,7 @@ impl DataModelExt for PaymentAttempt { preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model .mandate_details - .map(MandateDataType::from_storage_model), + .map(MandateTypeDetails::from_storage_model), error_reason: storage_model.error_reason, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, @@ -1231,7 +1276,7 @@ impl DataModelExt for PaymentAttemptNew { preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model .mandate_details - .map(MandateDataType::from_storage_model), + .map(MandateTypeDetails::from_storage_model), error_reason: storage_model.error_reason, connector_response_reference_id: storage_model.connector_response_reference_id, multiple_capture_count: storage_model.multiple_capture_count, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 7858029961a..09cb5fe1404 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -9026,6 +9026,11 @@ "MandateData": { "type": "object", "properties": { + "update_mandate_id": { + "type": "string", + "description": "A way to update the mandate's payment method details", + "nullable": true + }, "customer_acceptance": { "allOf": [ {
2024-01-24T18:22:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Update card_details for an existing mandate ### 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? - Create an MA and MCA(for connectors that support mandate) - Create a mandate payment with payment_type as `setup_mandate` - Now update the new card details with `mandate_data` with `mandate_type` as ``` "mandate_data": { "customer_acceptance" :.. "update_mandate_id":"{{existing_mandate_id}}" } ``` - The card gets updated for the existing mandate_id <img width="1195" alt="Screenshot 2024-01-25 at 12 08 25 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/0a093794-7fda-4016-a7d8-600f4608a658"> - List mandate for customer with that mandate_id <img width="1195" alt="Screenshot 2024-01-25 at 12 11 03 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/1b2de9b4-f640-4d83-abf3-8e5843ac4c78"> - Also the `connector_mandate_id` would we updated in the mandate table with all the past records with its past `payment_method_id` as well as `old_connector_mandate_id` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3fbffdc242dafe7983c542573b7c6362f99331e6
juspay/hyperswitch
juspay__hyperswitch-3428
Bug: Error: IncompleteMessage: connection closed before message completed ### Bug Description Intermittently few api calls gets closed with the following error `Error: IncompleteMessage: connection closed before message completed`. ### Expected Behavior The application should either kept the connection alive or retry connection. ### Actual Behavior The application is closing the connection and failing the API call Detailed hyper create issue: https://github.com/hyperium/hyper/issues/2136 ### Steps To Reproduce Let the application receive more load. For me, for every 1000 transactions, received one failure with this error. ### Context For The Bug Not able to talk to connector[basically it can be any outgoing call]. ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System : Linux ubuntu 2. Rust version (output of `rustc --version`): `rustc 1.74.0` 3. App version (output of `cargo r --features vergen -- --version`): `router 2024.01.08.0-75-gae83f28-ae83f28-2024-01-23T09:47:32.000000000Z` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 6c3293dba9d..a6d588bd43a 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -106,6 +106,7 @@ counter_metric!(APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT, GLOBAL_METER); counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT, GLOBAL_METER); // Metrics for Auto Retries +counter_metric!(AUTO_RETRY_CONNECTION_CLOSED, GLOBAL_METER); counter_metric!(AUTO_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_MISS_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER); diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 307dff55071..cf231895892 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -552,8 +552,7 @@ pub async fn send_request( key: consts::METRICS_HOST_TAG_NAME.into(), value: url.host_str().unwrap_or_default().to_string().into(), }; - - let send_request = async { + let request = { match request.method { Method::Get => client.get(url), Method::Post => { @@ -607,32 +606,92 @@ pub async fn send_request( .timeout(Duration::from_secs( option_timeout_secs.unwrap_or(crate::consts::REQUEST_TIME_OUT), )) - .send() - .await - .map_err(|error| match error { - error if error.is_timeout() => { - metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); - errors::ApiClientError::RequestTimeoutReceived - } - error if is_connection_closed(&error) => { - metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); - errors::ApiClientError::ConnectionClosed - } - _ => errors::ApiClientError::RequestNotSent(error.to_string()), - }) - .into_report() - .attach_printable("Unable to send request to connector") }; - metrics_request::record_operation_time( + // We cannot clone the request type, because it has Form trait which is not clonable. So we are cloning the request builder here. + let cloned_send_request = request.try_clone().map(|cloned_request| async { + cloned_request + .send() + .await + .map_err(|error| match error { + error if error.is_timeout() => { + metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); + errors::ApiClientError::RequestTimeoutReceived + } + error if is_connection_closed_before_message_could_complete(&error) => { + metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); + errors::ApiClientError::ConnectionClosedIncompleteMessage + } + _ => errors::ApiClientError::RequestNotSent(error.to_string()), + }) + .into_report() + .attach_printable("Unable to send request to connector") + }); + + let send_request = async { + request + .send() + .await + .map_err(|error| match error { + error if error.is_timeout() => { + metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); + errors::ApiClientError::RequestTimeoutReceived + } + error if is_connection_closed_before_message_could_complete(&error) => { + metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); + errors::ApiClientError::ConnectionClosedIncompleteMessage + } + _ => errors::ApiClientError::RequestNotSent(error.to_string()), + }) + .into_report() + .attach_printable("Unable to send request to connector") + }; + + let response = metrics_request::record_operation_time( send_request, &metrics::EXTERNAL_REQUEST_TIME, - &[metrics_tag], + &[metrics_tag.clone()], ) - .await + .await; + // Retry once if the response is connection closed. + // + // This is just due to the racy nature of networking. + // hyper has a connection pool of idle connections, and it selected one to send your request. + // Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool. + // But occasionally, a connection will be selected from the pool + // and written to at the same time the server is deciding to close the connection. + // Since hyper already wrote some of the request, + // it can’t really retry it automatically on a new connection, since the server may have acted already + match response { + Ok(response) => Ok(response), + Err(error) + if error.current_context() + == &errors::ApiClientError::ConnectionClosedIncompleteMessage => + { + metrics::AUTO_RETRY_CONNECTION_CLOSED.add(&metrics::CONTEXT, 1, &[]); + match cloned_send_request { + Some(cloned_request) => { + logger::info!( + "Retrying request due to connection closed before message could complete" + ); + metrics_request::record_operation_time( + cloned_request, + &metrics::EXTERNAL_REQUEST_TIME, + &[metrics_tag], + ) + .await + } + None => { + logger::info!("Retrying request due to connection closed before message could complete failed as request is not clonable"); + Err(error) + } + } + } + err @ Err(_) => err, + } } -fn is_connection_closed(error: &reqwest::Error) -> bool { +fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool { let mut source = error.source(); while let Some(err) = source { if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() { @@ -1674,7 +1733,7 @@ pub fn build_redirection_form( // Initialize the ThreeDSService const threeDS = gateway.get3DSecure(); - + const options = {{ customerVaultId: '{customer_vault_id}', currency: '{currency}', diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index ac3a04e85b2..46808a175c3 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -267,7 +267,7 @@ pub enum ApiClientError { RequestTimeoutReceived, #[error("connection closed before a message could complete")] - ConnectionClosed, + ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, @@ -285,8 +285,8 @@ impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } - pub fn is_connection_closed(&self) -> bool { - self == &Self::ConnectionClosed + pub fn is_connection_closed_before_message_could_complete(&self) -> bool { + self == &Self::ConnectionClosedIncompleteMessage } }
2024-01-23T09:45:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Hyper crate has a bug which allows few calls to connect with a dead connections and fails to send request to the server. This bug of hyper can be tracked with below link. `Error: IncompleteMessage: connection closed before message completed` - [Link](https://github.com/hyperium/hyper/issues/2136) Temporary fix: Retry connection with the server by sending the request again when call fails with this issue. Permanent fix would be, whenever reqwest crate release a stable version with hyper's 1.0 version [Another Link](https://epi052.github.io/feroxbuster-docs/docs/faq/connection-closed/) This is just due to the racy nature of networking. hyper has a connection pool of idle connections, and it selected one to send your request. Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool. But occasionally, a connection will be selected from the pool and written to at the same time the server is deciding to close the connection. Since hyper already wrote some of the request, it can’t really retry it automatically on a new connection, since the server may have acted already ### 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. `crates/router/src/configs/settings.rs` --> ## Motivation and Context Few external api calls fails due to this connection close ## How did you test it? Running the test case collections ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3fbffdc242dafe7983c542573b7c6362f99331e6
juspay/hyperswitch
juspay__hyperswitch-3439
Bug: [FEATURE] `Blocklist` initial implementation ### Feature Description: This feature provides merchants with the ability to customize their transaction controls based on specific criteria. Merchants can tailor the blocklist according to their preferences, blocking the following elements as needed: Card Numbers Card ISINs Extended BINs Understanding Blocklist: In the realm of payment processing, a blocklist serves as a security feature empowering merchants to restrict specific identifiers associated with payment methods or block certain card BINs. A fingerprint, a unique identifier linked to a payment method, and a card BIN, encompassing the first six digits of a credit card number, are key components. An extended card BIN covers the first eight digits. ### Testing Refer to the attached postman collection for the API contracts for the blocklist APIs. Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin. [blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip) ``` For Card Bin and Extended Card Bin :- 1. Setup a Merchant Account and any Connector account 2. Make a payment with a certain card (ensure it succeeds) 3. Block the card's card bin or extended card bin 4. Try the payment again (should fail this time with an API response saying that the payment was blocked) For Payment Instrument :- 1. Repeat steps 1 and 2 of previous section 2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card. 3. Try the payment again (should fail) ```
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs new file mode 100644 index 00000000000..fc838eed5ce --- /dev/null +++ b/crates/api_models/src/blocklist.rs @@ -0,0 +1,41 @@ +use common_enums::enums; +use common_utils::events::ApiEventMetric; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case", tag = "type", content = "data")] +pub enum BlocklistRequest { + CardBin(String), + Fingerprint(String), + ExtendedCardBin(String), +} + +pub type AddToBlocklistRequest = BlocklistRequest; +pub type DeleteFromBlocklistRequest = BlocklistRequest; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct BlocklistResponse { + pub fingerprint_id: String, + pub data_kind: enums::BlocklistDataKind, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: time::PrimitiveDateTime, +} + +pub type AddToBlocklistResponse = BlocklistResponse; +pub type DeleteFromBlocklistResponse = BlocklistResponse; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ListBlocklistQuery { + pub data_kind: enums::BlocklistDataKind, + #[serde(default = "default_list_limit")] + pub limit: u16, + #[serde(default)] + pub offset: u16, +} + +fn default_list_limit() -> u16 { + 10 +} + +impl ApiEventMetric for BlocklistRequest {} +impl ApiEventMetric for BlocklistResponse {} +impl ApiEventMetric for ListBlocklistQuery {} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 459443747e3..dc1f6eb6537 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -3,6 +3,7 @@ pub mod admin; pub mod analytics; pub mod api_keys; pub mod bank_accounts; +pub mod blocklist; pub mod cards_info; pub mod conditional_configs; pub mod connector_onboarding; diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 45611a91458..f9077500dd4 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2274,6 +2274,9 @@ pub struct PaymentsResponse { /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, + + /// Payment Fingerprint + pub fingerprint: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index ca47c73c7c2..87b04baa1a2 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -24,6 +24,13 @@ impl CardNumber { pub fn get_card_isin(self) -> String { self.0.peek().chars().take(6).collect::<String>() } + + pub fn get_extended_card_bin(self) -> String { + self.0.peek().chars().take(8).collect::<String>() + } + pub fn get_card_no(self) -> String { + self.0.peek().chars().collect::<String>() + } pub fn get_last4(self) -> String { self.0 .peek() diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 3af1c0e826b..949cc2e0034 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -6,12 +6,13 @@ use utoipa::ToSchema; pub mod diesel_exports { pub use super::{ DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, - DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, - DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, - DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventType as EventType, - DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, - DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, - DbPaymentType as PaymentType, DbRefundStatus as RefundStatus, + DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, + DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, + DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDisputeStage as DisputeStage, + DbDisputeStatus as DisputeStatus, DbEventType as EventType, DbFutureUsage as FutureUsage, + DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, + DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, + DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, }; } @@ -275,6 +276,27 @@ pub enum AuthorizationStatus { Unresolved, } +#[derive( + Clone, + Debug, + PartialEq, + Eq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, + Hash, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum BlocklistDataKind { + PaymentMethod, + CardBin, + ExtendedCardBin, +} + #[derive( Clone, Copy, diff --git a/crates/data_models/src/errors.rs b/crates/data_models/src/errors.rs index 9616a3a944c..bed1ab9ccbf 100644 --- a/crates/data_models/src/errors.rs +++ b/crates/data_models/src/errors.rs @@ -24,6 +24,8 @@ pub enum StorageError { SerializationFailed, #[error("MockDb error")] MockDbError, + #[error("Kafka error")] + KafkaError, #[error("Customer with this id is Redacted")] CustomerRedacted, #[error("Deserialization failure")] diff --git a/crates/data_models/src/payments.rs b/crates/data_models/src/payments.rs index cc6b03f89a5..713003d666b 100644 --- a/crates/data_models/src/payments.rs +++ b/crates/data_models/src/payments.rs @@ -53,5 +53,6 @@ pub struct PaymentIntent { pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, + pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, } diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs index 80671ec7f61..7470b5f8502 100644 --- a/crates/data_models/src/payments/payment_intent.rs +++ b/crates/data_models/src/payments/payment_intent.rs @@ -110,6 +110,7 @@ pub struct PaymentIntentNew { pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, + pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, } @@ -163,6 +164,7 @@ pub enum PaymentIntentUpdate { metadata: Option<pii::SecretSerdeValue>, payment_confirm_source: Option<storage_enums::PaymentSource>, updated_by: String, + fingerprint_id: Option<String>, session_expiry: Option<PrimitiveDateTime>, }, PaymentAttemptAndAttemptCountUpdate { @@ -228,6 +230,7 @@ pub struct PaymentIntentUpdateInternal { pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, + pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, } @@ -252,6 +255,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { metadata, payment_confirm_source, updated_by, + fingerprint_id, session_expiry, } => Self { amount: Some(amount), @@ -272,6 +276,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { metadata, payment_confirm_source, updated_by, + fingerprint_id, session_expiry, ..Default::default() }, diff --git a/crates/diesel_models/src/blocklist.rs b/crates/diesel_models/src/blocklist.rs new file mode 100644 index 00000000000..9e88802aa3b --- /dev/null +++ b/crates/diesel_models/src/blocklist.rs @@ -0,0 +1,26 @@ +use diesel::{Identifiable, Insertable, Queryable}; +use serde::{Deserialize, Serialize}; + +use crate::schema::blocklist; + +#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] +#[diesel(table_name = blocklist)] +pub struct BlocklistNew { + pub merchant_id: String, + pub fingerprint_id: String, + pub data_kind: common_enums::BlocklistDataKind, + pub metadata: Option<serde_json::Value>, + pub created_at: time::PrimitiveDateTime, +} + +#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Deserialize, Serialize)] +#[diesel(table_name = blocklist)] +pub struct Blocklist { + #[serde(skip)] + pub id: i32, + pub merchant_id: String, + pub fingerprint_id: String, + pub data_kind: common_enums::BlocklistDataKind, + pub metadata: Option<serde_json::Value>, + pub created_at: time::PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/blocklist_fingerprint.rs b/crates/diesel_models/src/blocklist_fingerprint.rs new file mode 100644 index 00000000000..e75856622e2 --- /dev/null +++ b/crates/diesel_models/src/blocklist_fingerprint.rs @@ -0,0 +1,26 @@ +use diesel::{Identifiable, Insertable, Queryable}; +use serde::{Deserialize, Serialize}; + +use crate::schema::blocklist_fingerprint; + +#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] +#[diesel(table_name = blocklist_fingerprint)] +pub struct BlocklistFingerprintNew { + pub merchant_id: String, + pub fingerprint_id: String, + pub data_kind: common_enums::BlocklistDataKind, + pub encrypted_fingerprint: String, + pub created_at: time::PrimitiveDateTime, +} + +#[derive(Clone, Debug, Eq, PartialEq, Queryable, Identifiable, Deserialize, Serialize)] +#[diesel(table_name = blocklist_fingerprint)] +pub struct BlocklistFingerprint { + #[serde(skip_serializing)] + pub id: i32, + pub merchant_id: String, + pub fingerprint_id: String, + pub data_kind: common_enums::BlocklistDataKind, + pub encrypted_fingerprint: String, + pub created_at: time::PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/blocklist_lookup.rs b/crates/diesel_models/src/blocklist_lookup.rs new file mode 100644 index 00000000000..ad2a893e03d --- /dev/null +++ b/crates/diesel_models/src/blocklist_lookup.rs @@ -0,0 +1,20 @@ +use diesel::{Identifiable, Insertable, Queryable}; +use serde::{Deserialize, Serialize}; + +use crate::schema::blocklist_lookup; + +#[derive(Default, Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] +#[diesel(table_name = blocklist_lookup)] +pub struct BlocklistLookupNew { + pub merchant_id: String, + pub fingerprint: String, +} + +#[derive(Default, Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Deserialize, Serialize)] +#[diesel(table_name = blocklist_lookup)] +pub struct BlocklistLookup { + #[serde(skip)] + pub id: i32, + pub merchant_id: String, + pub fingerprint: String, +} diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 792e8ffc8bb..a06937c99a6 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -2,9 +2,9 @@ pub mod diesel_exports { pub use super::{ DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, - DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, - DbConnectorStatus as ConnectorStatus, DbConnectorType as ConnectorType, - DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, + DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, + DbCaptureStatus as CaptureStatus, DbConnectorStatus as ConnectorStatus, + DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDashboardMetadata as DashboardMetadata, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index fa32fb84a15..82b1e29ee83 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -1,11 +1,14 @@ pub mod address; pub mod api_keys; +pub mod blocklist_lookup; pub mod business_profile; pub mod capture; pub mod cards_info; pub mod configs; pub mod authorization; +pub mod blocklist; +pub mod blocklist_fingerprint; pub mod customers; pub mod dispute; pub mod encryption; diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 17784bc5659..31bc0c06c51 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -56,6 +56,7 @@ pub struct PaymentIntent { pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, + pub fingerprint_id: Option<String>, } #[derive( @@ -107,6 +108,7 @@ pub struct PaymentIntentNew { pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, + pub fingerprint_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -160,6 +162,7 @@ pub enum PaymentIntentUpdate { payment_confirm_source: Option<storage_enums::PaymentSource>, updated_by: String, session_expiry: Option<PrimitiveDateTime>, + fingerprint_id: Option<String>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, @@ -226,6 +229,7 @@ pub struct PaymentIntentUpdateInternal { pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, + pub fingerprint_id: Option<String>, } impl PaymentIntentUpdate { @@ -259,6 +263,7 @@ impl PaymentIntentUpdate { incremental_authorization_allowed, authorization_count, session_expiry, + fingerprint_id, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), @@ -288,9 +293,11 @@ impl PaymentIntentUpdate { payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source), updated_by, surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), + incremental_authorization_allowed: incremental_authorization_allowed .or(source.incremental_authorization_allowed), authorization_count: authorization_count.or(source.authorization_count), + fingerprint_id: fingerprint_id.or(source.fingerprint_id), session_expiry: session_expiry.or(source.session_expiry), ..source } @@ -319,6 +326,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { payment_confirm_source, updated_by, session_expiry, + fingerprint_id, } => Self { amount: Some(amount), currency: Some(currency), @@ -339,6 +347,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { payment_confirm_source, updated_by, session_expiry, + fingerprint_id, ..Default::default() }, PaymentIntentUpdate::MetadataUpdate { diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 3a3dee47a85..3a0a008b76b 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -1,11 +1,14 @@ pub mod address; pub mod api_keys; +pub mod blocklist_lookup; pub mod business_profile; mod capture; pub mod cards_info; pub mod configs; pub mod authorization; +pub mod blocklist; +pub mod blocklist_fingerprint; pub mod customers; pub mod dashboard_metadata; pub mod dispute; diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rs new file mode 100644 index 00000000000..e1ba5fa923d --- /dev/null +++ b/crates/diesel_models/src/query/blocklist.rs @@ -0,0 +1,83 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + blocklist::{Blocklist, BlocklistNew}, + schema::blocklist::dsl, + PgPooledConn, StorageResult, +}; + +impl BlocklistNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Blocklist> { + generics::generic_insert(conn, self).await + } +} + +impl Blocklist { + #[instrument(skip(conn))] + pub async fn find_by_merchant_id_fingerprint_id( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint_id: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn list_by_merchant_id_data_kind( + conn: &PgPooledConn, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, + limit: i64, + offset: i64, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::data_kind.eq(data_kind.to_owned())), + Some(limit), + Some(offset), + Some(dsl::created_at.desc()), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn list_by_merchant_id( + conn: &PgPooledConn, + merchant_id: &str, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::merchant_id.eq(merchant_id.to_owned()), + None, + None, + Some(dsl::created_at.desc()), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn delete_by_merchant_id_fingerprint_id( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint_id: &str, + ) -> StorageResult<Self> { + generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), + ) + .await + } +} diff --git a/crates/diesel_models/src/query/blocklist_fingerprint.rs b/crates/diesel_models/src/query/blocklist_fingerprint.rs new file mode 100644 index 00000000000..4f3d77e63a8 --- /dev/null +++ b/crates/diesel_models/src/query/blocklist_fingerprint.rs @@ -0,0 +1,33 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew}, + schema::blocklist_fingerprint::dsl, + PgPooledConn, StorageResult, +}; + +impl BlocklistFingerprintNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistFingerprint> { + generics::generic_insert(conn, self).await + } +} + +impl BlocklistFingerprint { + #[instrument(skip(conn))] + pub async fn find_by_merchant_id_fingerprint_id( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint_id: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), + ) + .await + } +} diff --git a/crates/diesel_models/src/query/blocklist_lookup.rs b/crates/diesel_models/src/query/blocklist_lookup.rs new file mode 100644 index 00000000000..ea28c94e491 --- /dev/null +++ b/crates/diesel_models/src/query/blocklist_lookup.rs @@ -0,0 +1,48 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + blocklist_lookup::{BlocklistLookup, BlocklistLookupNew}, + schema::blocklist_lookup::dsl, + PgPooledConn, StorageResult, +}; + +impl BlocklistLookupNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistLookup> { + generics::generic_insert(conn, self).await + } +} + +impl BlocklistLookup { + #[instrument(skip(conn))] + pub async fn find_by_merchant_id_fingerprint( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint.eq(fingerprint.to_owned())), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn delete_by_merchant_id_fingerprint( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint: &str, + ) -> StorageResult<Self> { + generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint.eq(fingerprint.to_owned())), + ) + .await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index b29a362e3b0..131d2b18266 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -57,6 +57,50 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + blocklist (id) { + id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + fingerprint_id -> Varchar, + data_kind -> BlocklistDataKind, + metadata -> Nullable<Jsonb>, + created_at -> Timestamp, + } +} + +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + blocklist_fingerprint (id) { + id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + fingerprint_id -> Varchar, + data_kind -> BlocklistDataKind, + encrypted_fingerprint -> Text, + created_at -> Timestamp, + } +} + +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + blocklist_lookup (id) { + id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + fingerprint -> Text, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -709,6 +753,8 @@ diesel::table! { incremental_authorization_allowed -> Nullable<Bool>, authorization_count -> Nullable<Int4>, session_expiry -> Nullable<Timestamp>, + #[max_length = 64] + fingerprint_id -> Nullable<Varchar>, } } @@ -1016,6 +1062,9 @@ diesel::table! { diesel::allow_tables_to_appear_in_same_query!( address, api_keys, + blocklist, + blocklist_fingerprint, + blocklist_lookup, business_profile, captures, cards_info, diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 5963110c632..63205ea68ca 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -520,6 +520,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { connector_name, }, errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, + errors::ApiErrorResponse::PaymentBlocked => Self::PaymentFailed, errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { param: "client_secret".to_owned(), }, diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index afe76184630..ed020b0c7e0 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -27,6 +27,9 @@ pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60; /// Payment intent default client secret expiry (in seconds) pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60; +/// The length of a merchant fingerprint secret +pub const FINGERPRINT_SECRET_LENGTH: usize = 64; + // String literals pub(crate) const NO_ERROR_MESSAGE: &str = "No error message"; pub(crate) const NO_ERROR_CODE: &str = "No error code"; diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 0bd197ee22e..5ae4b0be33d 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -1,6 +1,7 @@ pub mod admin; pub mod api_keys; pub mod api_locking; +pub mod blocklist; pub mod cache; pub mod cards_info; pub mod conditional_config; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 2577bb83a3a..e8593581126 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -10,6 +10,7 @@ use common_utils::{ ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, pii, }; +use diesel_models::configs; use error_stack::{report, FutureExt, IntoReport, ResultExt}; use futures::future::try_join_all; use masking::{PeekInterface, Secret}; @@ -141,6 +142,17 @@ pub async fn create_merchant_account( .transpose()? .map(Secret::new); + let fingerprint = Some(utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs")); + if let Some(fingerprint) = fingerprint { + db.insert_config(configs::ConfigNew { + key: format!("fingerprint_secret_{}", req.merchant_id), + config: fingerprint, + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Mot able to generate Merchant fingerprint")?; + }; + let organization_id = if let Some(organization_id) = req.organization_id.as_ref() { db.find_organization_by_org_id(organization_id) .await diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rs new file mode 100644 index 00000000000..85845602449 --- /dev/null +++ b/crates/router/src/core/blocklist.rs @@ -0,0 +1,41 @@ +pub mod transformers; +pub mod utils; + +use api_models::blocklist as api_blocklist; + +use crate::{ + core::errors::{self, RouterResponse}, + routes::AppState, + services, + types::domain, +}; + +pub async fn add_entry_to_blocklist( + state: AppState, + merchant_account: domain::MerchantAccount, + body: api_blocklist::AddToBlocklistRequest, +) -> RouterResponse<api_blocklist::AddToBlocklistResponse> { + utils::insert_entry_into_blocklist(&state, merchant_account.merchant_id, body) + .await + .map(services::ApplicationResponse::Json) +} + +pub async fn remove_entry_from_blocklist( + state: AppState, + merchant_account: domain::MerchantAccount, + body: api_blocklist::DeleteFromBlocklistRequest, +) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> { + utils::delete_entry_from_blocklist(&state, merchant_account.merchant_id, body) + .await + .map(services::ApplicationResponse::Json) +} + +pub async fn list_blocklist_entries( + state: AppState, + merchant_account: domain::MerchantAccount, + query: api_blocklist::ListBlocklistQuery, +) -> RouterResponse<Vec<api_blocklist::BlocklistResponse>> { + utils::list_blocklist_entries_for_merchant(&state, merchant_account.merchant_id, query) + .await + .map(services::ApplicationResponse::Json) +} diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rs new file mode 100644 index 00000000000..2cb5f86a264 --- /dev/null +++ b/crates/router/src/core/blocklist/transformers.rs @@ -0,0 +1,13 @@ +use api_models::blocklist; + +use crate::types::{storage, transformers::ForeignFrom}; + +impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse { + fn foreign_from(from: storage::Blocklist) -> Self { + Self { + fingerprint_id: from.fingerprint_id, + data_kind: from.data_kind, + created_at: from.created_at, + } + } +} diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs new file mode 100644 index 00000000000..b7effaf63ac --- /dev/null +++ b/crates/router/src/core/blocklist/utils.rs @@ -0,0 +1,359 @@ +use api_models::blocklist as api_blocklist; +use common_utils::crypto::{self, SignMessage}; +use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "kms")] +use external_services::kms; + +use super::{errors, AppState}; +use crate::{ + consts, + core::errors::{RouterResult, StorageErrorExt}, + types::{storage, transformers::ForeignInto}, + utils, +}; + +pub async fn delete_entry_from_blocklist( + state: &AppState, + merchant_id: String, + request: api_blocklist::DeleteFromBlocklistRequest, +) -> RouterResult<api_blocklist::DeleteFromBlocklistResponse> { + let blocklist_entry = match request { + api_blocklist::DeleteFromBlocklistRequest::CardBin(bin) => { + delete_card_bin_blocklist_entry(state, &bin, &merchant_id).await? + } + + api_blocklist::DeleteFromBlocklistRequest::ExtendedCardBin(xbin) => { + delete_card_bin_blocklist_entry(state, &xbin, &merchant_id).await? + } + + api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => { + let blocklist_fingerprint = state + .store + .find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &merchant_id, + &fingerprint_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "blocklist record with given fingerprint id not found".to_string(), + })?; + + #[cfg(feature = "kms")] + let decrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + .await + .decrypt(blocklist_fingerprint.encrypted_fingerprint) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to kms decrypt fingerprint")?; + + #[cfg(not(feature = "kms"))] + let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; + + let blocklist_entry = state + .store + .delete_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, &fingerprint_id) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "no blocklist record for the given fingerprint id was found" + .to_string(), + })?; + + state + .store + .delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + &decrypted_fingerprint, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "no blocklist record for the given fingerprint id was found" + .to_string(), + })?; + + blocklist_entry + } + }; + + Ok(blocklist_entry.foreign_into()) +} + +pub async fn list_blocklist_entries_for_merchant( + state: &AppState, + merchant_id: String, + query: api_blocklist::ListBlocklistQuery, +) -> RouterResult<Vec<api_blocklist::BlocklistResponse>> { + state + .store + .list_blocklist_entries_by_merchant_id_data_kind( + &merchant_id, + query.data_kind, + query.limit.into(), + query.offset.into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "no blocklist records found".to_string(), + }) + .map(|v| v.into_iter().map(ForeignInto::foreign_into).collect()) +} + +fn validate_card_bin(bin: &str) -> RouterResult<()> { + if bin.len() == 6 && bin.chars().all(|c| c.is_ascii_digit()) { + Ok(()) + } else { + Err(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "data".to_string(), + expected_format: "a 6 digit number".to_string(), + }) + .into_report() + } +} + +fn validate_extended_card_bin(bin: &str) -> RouterResult<()> { + if bin.len() == 8 && bin.chars().all(|c| c.is_ascii_digit()) { + Ok(()) + } else { + Err(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "data".to_string(), + expected_format: "an 8 digit number".to_string(), + }) + .into_report() + } +} + +pub async fn insert_entry_into_blocklist( + state: &AppState, + merchant_id: String, + to_block: api_blocklist::AddToBlocklistRequest, +) -> RouterResult<api_blocklist::AddToBlocklistResponse> { + let blocklist_entry = match &to_block { + api_blocklist::AddToBlocklistRequest::CardBin(bin) => { + validate_card_bin(bin)?; + duplicate_check_insert_bin( + bin, + state, + &merchant_id, + common_enums::BlocklistDataKind::CardBin, + ) + .await? + } + + api_blocklist::AddToBlocklistRequest::ExtendedCardBin(bin) => { + validate_extended_card_bin(bin)?; + duplicate_check_insert_bin( + bin, + state, + &merchant_id, + common_enums::BlocklistDataKind::ExtendedCardBin, + ) + .await? + } + + api_blocklist::AddToBlocklistRequest::Fingerprint(fingerprint_id) => { + let blocklist_entry_result = state + .store + .find_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, fingerprint_id) + .await; + + match blocklist_entry_result { + Ok(_) => { + return Err(errors::ApiErrorResponse::PreconditionFailed { + message: "data associated with the given fingerprint is already blocked" + .to_string(), + }) + .into_report(); + } + + // if it is a db not found error, we can proceed as normal + Err(inner) if inner.current_context().is_db_not_found() => {} + + err @ Err(_) => { + err.change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error fetching blocklist entry from table")?; + } + } + + let blocklist_fingerprint = state + .store + .find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &merchant_id, + fingerprint_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "fingerprint not found".to_string(), + })?; + + #[cfg(feature = "kms")] + let decrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + .await + .decrypt(blocklist_fingerprint.encrypted_fingerprint) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to kms decrypt encrypted fingerprint")?; + + #[cfg(not(feature = "kms"))] + let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; + + state + .store + .insert_blocklist_lookup_entry( + diesel_models::blocklist_lookup::BlocklistLookupNew { + merchant_id: merchant_id.clone(), + fingerprint: decrypted_fingerprint, + }, + ) + .await + .to_duplicate_response(errors::ApiErrorResponse::PreconditionFailed { + message: "the payment instrument associated with the given fingerprint is already in the blocklist".to_string(), + }) + .attach_printable("failed to add fingerprint to blocklist lookup")?; + + state + .store + .insert_blocklist_entry(storage::BlocklistNew { + merchant_id: merchant_id.clone(), + fingerprint_id: fingerprint_id.clone(), + data_kind: blocklist_fingerprint.data_kind, + metadata: None, + created_at: common_utils::date_time::now(), + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to add fingerprint to pm blocklist")? + } + }; + + Ok(blocklist_entry.foreign_into()) +} + +pub async fn get_merchant_fingerprint_secret( + state: &AppState, + merchant_id: &str, +) -> RouterResult<String> { + let key = get_merchant_fingerprint_secret_key(merchant_id); + let config_fetch_result = state.store.find_config_by_key(&key).await; + + match config_fetch_result { + Ok(config) => Ok(config.config), + + Err(e) if e.current_context().is_db_not_found() => { + let new_fingerprint_secret = + utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs"); + let new_config = storage::ConfigNew { + key, + config: new_fingerprint_secret.clone(), + }; + + state + .store + .insert_config(new_config) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to create new fingerprint secret for merchant")?; + + Ok(new_fingerprint_secret) + } + + Err(e) => Err(e) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error fetching merchant fingerprint secret"), + } +} + +pub fn get_merchant_fingerprint_secret_key(merchant_id: &str) -> String { + format!("fingerprint_secret_{merchant_id}") +} + +async fn duplicate_check_insert_bin( + bin: &str, + state: &AppState, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, +) -> RouterResult<storage::Blocklist> { + let merchant_secret = get_merchant_fingerprint_secret(state, merchant_id).await?; + let bin_fingerprint = crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_secret.clone().as_bytes(), + bin.as_bytes(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error in bin hash creation")?; + + let encoded_fingerprint = hex::encode(bin_fingerprint.clone()); + + let blocklist_entry_result = state + .store + .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin) + .await; + + match blocklist_entry_result { + Ok(_) => { + return Err(errors::ApiErrorResponse::PreconditionFailed { + message: "provided bin is already blocked".to_string(), + }) + .into_report(); + } + + Err(e) if e.current_context().is_db_not_found() => {} + + err @ Err(_) => { + return err + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to fetch blocklist entry"); + } + } + + // Checking for duplicacy + state + .store + .insert_blocklist_lookup_entry(diesel_models::blocklist_lookup::BlocklistLookupNew { + merchant_id: merchant_id.to_string(), + fingerprint: encoded_fingerprint.clone(), + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error inserting blocklist lookup entry")?; + + state + .store + .insert_blocklist_entry(storage::BlocklistNew { + merchant_id: merchant_id.to_string(), + fingerprint_id: bin.to_string(), + data_kind, + metadata: None, + created_at: common_utils::date_time::now(), + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error inserting pm blocklist item") +} + +async fn delete_card_bin_blocklist_entry( + state: &AppState, + bin: &str, + merchant_id: &str, +) -> RouterResult<storage::Blocklist> { + let merchant_secret = get_merchant_fingerprint_secret(state, merchant_id).await?; + let bin_fingerprint = crypto::HmacSha512 + .sign_message(merchant_secret.as_bytes(), bin.as_bytes()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error when hashing card bin")?; + let encoded_fingerprint = hex::encode(bin_fingerprint); + + state + .store + .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, &encoded_fingerprint) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "could not find a blocklist entry for the given bin".to_string(), + })?; + + state + .store + .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "could not find a blocklist entry for the given bin".to_string(), + }) +} diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index f94504cf274..54ec4ec1e29 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -186,6 +186,8 @@ pub enum ApiErrorResponse { PaymentNotSucceeded, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")] MerchantConnectorAccountDisabled, + #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified payment is blocked")] + PaymentBlocked, #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")] diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs index fa9a5185790..ff764cafed6 100644 --- a/crates/router/src/core/errors/transformers.rs +++ b/crates/router/src/core/errors/transformers.rs @@ -187,6 +187,7 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.clone()), ..Default::default() }))) } Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)), + Self::PaymentBlocked => AER::BadRequest(ApiError::new("HE", 3, "The payment is blocked", None)), Self::SuccessfulPaymentNotFound => { AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None)) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index ec6371f310f..003c09b7381 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2586,6 +2586,7 @@ mod tests { modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: None, + fingerprint_id: None, off_session: None, client_secret: Some("1".to_string()), active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()), @@ -2638,6 +2639,7 @@ mod tests { statement_descriptor_suffix: None, created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)), modified_at: common_utils::date_time::now(), + fingerprint_id: None, last_synced: None, setup_future_usage: None, off_session: None, @@ -2695,6 +2697,7 @@ mod tests { setup_future_usage: None, off_session: None, client_secret: None, + fingerprint_id: None, active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()), business_country: None, business_label: None, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 00ae8da6ae4..c81145c5de7 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -2,23 +2,30 @@ use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; -use common_utils::ext_traits::{AsyncExt, Encode}; +use common_utils::{ + crypto::{self, SignMessage}, + ext_traits::{AsyncExt, Encode}, +}; use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "kms")] +use external_services::kms; use futures::FutureExt; use router_derive::PaymentOperation; -use router_env::{instrument, tracing}; +use router_env::{instrument, logger, tracing}; use tracing_futures::Instrument; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ + consts, core::{ + blocklist::utils as blocklist_utils, errors::{self, CustomResult, RouterResult, StorageErrorExt}, payment_methods::PaymentMethodRetrieve, payments::{ self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress, PaymentData, }, - utils::{self as core_utils}, + utils as core_utils, }, db::StorageInterface, routes::AppState, @@ -620,32 +627,34 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> where F: 'b + Send, { + let db = state.store.as_ref(); let payment_method = payment_data.payment_attempt.payment_method; let browser_info = payment_data.payment_attempt.browser_info.clone(); let frm_message = payment_data.frm_message.clone(); - let (intent_status, attempt_status, (error_code, error_message)) = match frm_suggestion { - Some(FrmSuggestion::FrmCancelTransaction) => ( - storage_enums::IntentStatus::Failed, - storage_enums::AttemptStatus::Failure, - frm_message.map_or((None, None), |fraud_check| { - ( - Some(Some(fraud_check.frm_status.to_string())), - Some(fraud_check.frm_reason.map(|reason| reason.to_string())), - ) - }), - ), - Some(FrmSuggestion::FrmManualReview) => ( - storage_enums::IntentStatus::RequiresMerchantAction, - storage_enums::AttemptStatus::Unresolved, - (None, None), - ), - _ => ( - storage_enums::IntentStatus::Processing, - storage_enums::AttemptStatus::Pending, - (None, None), - ), - }; + let (mut intent_status, mut attempt_status, (error_code, error_message)) = + match frm_suggestion { + Some(FrmSuggestion::FrmCancelTransaction) => ( + storage_enums::IntentStatus::Failed, + storage_enums::AttemptStatus::Failure, + frm_message.map_or((None, None), |fraud_check| { + ( + Some(Some(fraud_check.frm_status.to_string())), + Some(fraud_check.frm_reason.map(|reason| reason.to_string())), + ) + }), + ), + Some(FrmSuggestion::FrmManualReview) => ( + storage_enums::IntentStatus::RequiresMerchantAction, + storage_enums::AttemptStatus::Unresolved, + (None, None), + ), + _ => ( + storage_enums::IntentStatus::Processing, + storage_enums::AttemptStatus::Pending, + (None, None), + ), + }; let connector = payment_data.payment_attempt.connector.clone(); let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone(); @@ -709,6 +718,157 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> let m_error_message = error_message.clone(); let m_db = state.clone().store; + // Validate Blocklist + let merchant_id = payment_data.payment_attempt.merchant_id; + let merchant_fingerprint_secret = + blocklist_utils::get_merchant_fingerprint_secret(state, &merchant_id).await?; + + // Hashed Fingerprint to check whether or not this payment should be blocked. + let card_number_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_card_no().as_bytes(), + ) + .attach_printable("error in pm fingerprint creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + // Hashed Cardbin to check whether or not this payment should be blocked. + let card_bin_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_card_isin().as_bytes(), + ) + .attach_printable("error in card bin hash creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + // Hashed Extended Cardbin to check whether or not this payment should be blocked. + let extended_card_bin_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_extended_card_bin().as_bytes(), + ) + .attach_printable("error in extended card bin hash creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + let mut fingerprint_id = None; + + //validating the payment method. + let mut is_pm_blocklisted = false; + + let mut blocklist_futures = Vec::new(); + if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + card_number_fingerprint, + )); + } + + if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + card_bin_fingerprint, + )); + } + + if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + extended_card_bin_fingerprint, + )); + } + + let blocklist_lookups = futures::future::join_all(blocklist_futures).await; + + if blocklist_lookups.iter().any(|x| x.is_ok()) { + intent_status = storage_enums::IntentStatus::Failed; + attempt_status = storage_enums::AttemptStatus::Failure; + is_pm_blocklisted = true; + } + + if let Some(encoded_hash) = card_number_fingerprint { + #[cfg(feature = "kms")] + let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + .await + .encrypt(encoded_hash) + .await + .map_or_else( + |e| { + logger::error!(error=?e, "failed kms encryption of card fingerprint"); + None + }, + Some, + ); + + #[cfg(not(feature = "kms"))] + let encrypted_fingerprint = Some(encoded_hash); + + if let Some(encrypted_fingerprint) = encrypted_fingerprint { + fingerprint_id = db + .insert_blocklist_fingerprint_entry( + diesel_models::blocklist_fingerprint::BlocklistFingerprintNew { + merchant_id, + fingerprint_id: utils::generate_id(consts::ID_LENGTH, "fingerprint"), + encrypted_fingerprint, + data_kind: common_enums::BlocklistDataKind::PaymentMethod, + created_at: common_utils::date_time::now(), + }, + ) + .await + .map_or_else( + |e| { + logger::error!(error=?e, "failed storing card fingerprint in db"); + None + }, + |fp| Some(fp.fingerprint_id), + ); + } + } + let surcharge_amount = payment_data .surcharge_details .as_ref() @@ -789,6 +949,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> metadata: m_metadata, payment_confirm_source: header_payload.payment_confirm_source, updated_by: m_storage_scheme, + fingerprint_id, session_expiry, }, storage_scheme, @@ -838,6 +999,11 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> payment_data.payment_intent = payment_intent; payment_data.payment_attempt = payment_attempt; + // Block the payment if the entry was present in the Blocklist + if is_pm_blocklisted { + return Err(errors::ApiErrorResponse::PaymentBlocked.into()); + } + Ok((Box::new(self), payment_data)) } } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 09ec436ed00..2b25a74deb1 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -825,6 +825,7 @@ impl PaymentCreate { request_incremental_authorization, incremental_authorization_allowed: None, authorization_count: None, + fingerprint_id: None, session_expiry: Some(session_expiry), }) } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index afb83d38dc5..e002b92d181 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -617,6 +617,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> metadata, payment_confirm_source: None, updated_by: storage_scheme.to_string(), + fingerprint_id: None, session_expiry, }, storage_scheme, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7b7d64a5f81..c3f52618f0a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -706,6 +706,7 @@ where .set_incremental_authorization_allowed( payment_intent.incremental_authorization_allowed, ) + .set_fingerprint(payment_intent.fingerprint_id) .set_authorization_count(payment_intent.authorization_count) .set_incremental_authorizations(incremental_authorizations_response) .to_owned(), diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 5beace9cbb8..b9d346b7a71 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -1,6 +1,9 @@ pub mod address; pub mod api_keys; pub mod authorization; +pub mod blocklist; +pub mod blocklist_fingerprint; +pub mod blocklist_lookup; pub mod business_profile; pub mod cache; pub mod capture; @@ -68,6 +71,7 @@ pub trait StorageInterface: + dyn_clone::DynClone + address::AddressInterface + api_keys::ApiKeyInterface + + blocklist_lookup::BlocklistLookupInterface + configs::ConfigInterface + capture::CaptureInterface + customers::CustomerInterface @@ -85,6 +89,8 @@ pub trait StorageInterface: + PaymentAttemptInterface + PaymentIntentInterface + payment_method::PaymentMethodInterface + + blocklist::BlocklistInterface + + blocklist_fingerprint::BlocklistFingerprintInterface + scheduler::SchedulerInterface + payout_attempt::PayoutAttemptInterface + payouts::PayoutsInterface diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rs new file mode 100644 index 00000000000..c263bef63c5 --- /dev/null +++ b/crates/router/src/db/blocklist.rs @@ -0,0 +1,203 @@ +use error_stack::IntoReport; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait BlocklistInterface { + async fn insert_blocklist_entry( + &self, + pm_blocklist_new: storage::BlocklistNew, + ) -> CustomResult<storage::Blocklist, errors::StorageError>; + + async fn find_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError>; + + async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError>; + + async fn list_blocklist_entries_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; + + async fn list_blocklist_entries_by_merchant_id_data_kind( + &self, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; +} + +#[async_trait::async_trait] +impl BlocklistInterface for Store { + #[instrument(skip_all)] + async fn insert_blocklist_entry( + &self, + pm_blocklist: storage::BlocklistNew, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + pm_blocklist + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } + + async fn find_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Blocklist::find_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn list_blocklist_entries_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Blocklist::list_by_merchant_id(&conn, merchant_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn list_blocklist_entries_by_merchant_id_data_kind( + &self, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Blocklist::list_by_merchant_id_data_kind( + &conn, + merchant_id, + data_kind, + limit, + offset, + ) + .await + .map_err(Into::into) + .into_report() + } + + async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Blocklist::delete_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl BlocklistInterface for MockDb { + #[instrument(skip_all)] + async fn insert_blocklist_entry( + &self, + _pm_blocklist: storage::BlocklistNew, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn find_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn list_blocklist_entries_by_merchant_id( + &self, + _merchant_id: &str, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn list_blocklist_entries_by_merchant_id_data_kind( + &self, + _merchant_id: &str, + _data_kind: common_enums::BlocklistDataKind, + _limit: i64, + _offset: i64, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl BlocklistInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_blocklist_entry( + &self, + _pm_blocklist: storage::BlocklistNew, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn find_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn list_blocklist_entries_by_merchant_id_data_kind( + &self, + _merchant_id: &str, + _data_kind: common_enums::BlocklistDataKind, + _limit: i64, + _offset: i64, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn list_blocklist_entries_by_merchant_id( + &self, + _merchant_id: &str, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } +} diff --git a/crates/router/src/db/blocklist_fingerprint.rs b/crates/router/src/db/blocklist_fingerprint.rs new file mode 100644 index 00000000000..9da7c7d8fb2 --- /dev/null +++ b/crates/router/src/db/blocklist_fingerprint.rs @@ -0,0 +1,95 @@ +use error_stack::IntoReport; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait BlocklistFingerprintInterface { + async fn insert_blocklist_fingerprint_entry( + &self, + pm_fingerprint_new: storage::BlocklistFingerprintNew, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; + + async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; +} + +#[async_trait::async_trait] +impl BlocklistFingerprintInterface for Store { + #[instrument(skip_all)] + async fn insert_blocklist_fingerprint_entry( + &self, + pm_fingerprint_new: storage::BlocklistFingerprintNew, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + pm_fingerprint_new + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } + + async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::BlocklistFingerprint::find_by_merchant_id_fingerprint_id( + &conn, + merchant_id, + fingerprint_id, + ) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl BlocklistFingerprintInterface for MockDb { + #[instrument(skip_all)] + async fn insert_blocklist_fingerprint_entry( + &self, + _pm_fingerprint_new: storage::BlocklistFingerprintNew, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl BlocklistFingerprintInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_blocklist_fingerprint_entry( + &self, + _pm_fingerprint_new: storage::BlocklistFingerprintNew, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } +} diff --git a/crates/router/src/db/blocklist_lookup.rs b/crates/router/src/db/blocklist_lookup.rs new file mode 100644 index 00000000000..0dfd81c8b8a --- /dev/null +++ b/crates/router/src/db/blocklist_lookup.rs @@ -0,0 +1,125 @@ +use error_stack::IntoReport; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait BlocklistLookupInterface { + async fn insert_blocklist_lookup_entry( + &self, + blocklist_lookup_new: storage::BlocklistLookupNew, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; + + async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + merchant_id: &str, + fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; + + async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + merchant_id: &str, + fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; +} + +#[async_trait::async_trait] +impl BlocklistLookupInterface for Store { + #[instrument(skip_all)] + async fn insert_blocklist_lookup_entry( + &self, + blocklist_lookup_entry: storage::BlocklistLookupNew, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + blocklist_lookup_entry + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } + + async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + merchant_id: &str, + fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::BlocklistLookup::find_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) + .await + .map_err(Into::into) + .into_report() + } + + async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + merchant_id: &str, + fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::BlocklistLookup::delete_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl BlocklistLookupInterface for MockDb { + #[instrument(skip_all)] + async fn insert_blocklist_lookup_entry( + &self, + _blocklist_lookup_entry: storage::BlocklistLookupNew, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + _merchant_id: &str, + _fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + _merchant_id: &str, + _fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl BlocklistLookupInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_blocklist_lookup_entry( + &self, + _blocklist_lookup_entry: storage::BlocklistLookupNew, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + _merchant_id: &str, + _fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + _merchant_id: &str, + _fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 3b4c7ce9b7d..696198f2153 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -129,9 +129,9 @@ pub fn mk_app( #[cfg(feature = "oltp")] { server_app = server_app - .service(routes::PaymentMethods::server(state.clone())) .service(routes::EphemeralKey::server(state.clone())) .service(routes::Webhooks::server(state.clone())) + .service(routes::PaymentMethods::server(state.clone())) } #[cfg(feature = "olap")] @@ -143,6 +143,7 @@ pub fn mk_app( .service(routes::Disputes::server(state.clone())) .service(routes::Analytics::server(state.clone())) .service(routes::Routing::server(state.clone())) + .service(routes::Blocklist::server(state.clone())) .service(routes::LockerMigrate::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index ec718b2dde9..d4bfabb6f92 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -1,6 +1,8 @@ pub mod admin; pub mod api_keys; pub mod app; +#[cfg(feature = "olap")] +pub mod blocklist; pub mod cache; pub mod cards_info; pub mod configs; @@ -42,14 +44,15 @@ pub mod webhooks; pub mod locker_migration; #[cfg(any(feature = "olap", feature = "oltp"))] pub mod pm_auth; +#[cfg(feature = "olap")] +pub use app::{Blocklist, Routing}; + #[cfg(feature = "dummy_connector")] pub use self::app::DummyConnector; #[cfg(any(feature = "olap", feature = "oltp"))] pub use self::app::Forex; #[cfg(feature = "payouts")] pub use self::app::Payouts; -#[cfg(feature = "olap")] -pub use self::app::Routing; #[cfg(all(feature = "olap", feature = "kms"))] pub use self::app::Verify; pub use self::app::{ diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6625a206be2..0efe2218a9a 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -14,6 +14,8 @@ use scheduler::SchedulerInterface; use storage_impl::MockDb; use tokio::sync::oneshot; +#[cfg(feature = "olap")] +use super::blocklist; #[cfg(any(feature = "olap", feature = "oltp"))] use super::currency; #[cfg(feature = "dummy_connector")] @@ -566,6 +568,23 @@ impl PaymentMethods { } } +#[cfg(feature = "olap")] +pub struct Blocklist; + +#[cfg(feature = "olap")] +impl Blocklist { + pub fn server(state: AppState) -> Scope { + web::scope("/blocklist") + .app_data(web::Data::new(state)) + .service( + web::resource("") + .route(web::get().to(blocklist::list_blocked_payment_methods)) + .route(web::post().to(blocklist::add_entry_to_blocklist)) + .route(web::delete().to(blocklist::remove_entry_from_blocklist)), + ) + } +} + pub struct MerchantAccount; #[cfg(feature = "olap")] diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs new file mode 100644 index 00000000000..7c268dddeec --- /dev/null +++ b/crates/router/src/routes/blocklist.rs @@ -0,0 +1,81 @@ +use actix_web::{web, HttpRequest, HttpResponse}; +use api_models::blocklist as api_blocklist; +use router_env::Flow; + +use crate::{ + core::{api_locking, blocklist}, + routes::AppState, + services::{api, authentication as auth, authorization::permissions::Permission}, +}; + +pub async fn add_entry_to_blocklist( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_blocklist::AddToBlocklistRequest>, +) -> HttpResponse { + let flow = Flow::AddToBlocklist; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, body| { + blocklist::add_entry_to_blocklist(state, auth.merchant_account, body) + }, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::MerchantAccountWrite), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn remove_entry_from_blocklist( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_blocklist::DeleteFromBlocklistRequest>, +) -> HttpResponse { + let flow = Flow::DeleteFromBlocklist; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, body| { + blocklist::remove_entry_from_blocklist(state, auth.merchant_account, body) + }, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::MerchantAccountWrite), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn list_blocked_payment_methods( + state: web::Data<AppState>, + req: HttpRequest, + query_payload: web::Query<api_blocklist::ListBlocklistQuery>, +) -> HttpResponse { + let flow = Flow::ListBlocklist; + Box::pin(api::server_wrap( + flow, + state, + &req, + query_payload.into_inner(), + |state, auth: auth::AuthenticationData, query| { + blocklist::list_blocklist_entries(state, auth.merchant_account, query) + }, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::MerchantAccountRead), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 10f408f3d4f..55c6cbc23d7 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -24,6 +24,7 @@ pub enum ApiIdentifier { ApiKeys, PaymentLink, Routing, + Blocklist, Forex, RustLockerMigration, Gsm, @@ -57,6 +58,10 @@ impl From<Flow> for ApiIdentifier { Flow::RetrieveForexFlow => Self::Forex, + Flow::AddToBlocklist => Self::Blocklist, + Flow::DeleteFromBlocklist => Self::Blocklist, + Flow::ListBlocklist => Self::Blocklist, + Flow::MerchantConnectorsCreate | Flow::MerchantConnectorsRetrieve | Flow::MerchantConnectorsUpdate diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 56d3272b947..b93cbbbbba9 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -1,6 +1,9 @@ pub mod address; pub mod api_keys; pub mod authorization; +pub mod blocklist; +pub mod blocklist_fingerprint; +pub mod blocklist_lookup; pub mod business_profile; pub mod capture; pub mod cards_info; @@ -43,7 +46,8 @@ pub use diesel_models::{ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate} pub use scheduler::db::process_tracker; pub use self::{ - address::*, api_keys::*, authorization::*, capture::*, cards_info::*, configs::*, customers::*, + address::*, api_keys::*, authorization::*, blocklist::*, blocklist_fingerprint::*, + blocklist_lookup::*, capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*, ephemeral_key::*, events::*, file::*, fraud_check::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, payout_attempt::*, payouts::*, diff --git a/crates/router/src/types/storage/blocklist.rs b/crates/router/src/types/storage/blocklist.rs new file mode 100644 index 00000000000..7e7648dd4a0 --- /dev/null +++ b/crates/router/src/types/storage/blocklist.rs @@ -0,0 +1 @@ +pub use diesel_models::blocklist::{Blocklist, BlocklistNew}; diff --git a/crates/router/src/types/storage/blocklist_fingerprint.rs b/crates/router/src/types/storage/blocklist_fingerprint.rs new file mode 100644 index 00000000000..092d881e3fa --- /dev/null +++ b/crates/router/src/types/storage/blocklist_fingerprint.rs @@ -0,0 +1 @@ +pub use diesel_models::blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew}; diff --git a/crates/router/src/types/storage/blocklist_lookup.rs b/crates/router/src/types/storage/blocklist_lookup.rs new file mode 100644 index 00000000000..978708ff7c3 --- /dev/null +++ b/crates/router/src/types/storage/blocklist_lookup.rs @@ -0,0 +1 @@ +pub use diesel_models::blocklist_lookup::{BlocklistLookup, BlocklistLookupNew}; diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 33f1e211534..dcf635595e0 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -199,6 +199,7 @@ pub async fn generate_sample_data( request_incremental_authorization: Default::default(), incremental_authorization_allowed: Default::default(), authorization_count: Default::default(), + fingerprint_id: None, session_expiry: Some(session_expiry), }; let payment_attempt = PaymentAttemptBatchNew { diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index e37e15443bd..a6ac1b1e0a1 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -185,6 +185,12 @@ pub enum Flow { RoutingUpdateDefaultConfig, /// Routing delete config RoutingDeleteConfig, + /// Add record to blocklist + AddToBlocklist, + /// Delete record from blocklist + DeleteFromBlocklist, + /// List entries from blocklist + ListBlocklist, /// Incoming Webhook Receive IncomingWebhookReceive, /// Validate payment method flow diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 50173bb1c73..ac3a04e85b2 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -55,6 +55,8 @@ pub enum StorageError { SerializationFailed, #[error("MockDb error")] MockDbError, + #[error("Kafka error")] + KafkaError, #[error("Customer with this id is Redacted")] CustomerRedacted, #[error("Deserialization failure")] @@ -103,6 +105,7 @@ impl Into<DataStorageError> for &StorageError { StorageError::KVError => DataStorageError::KVError, StorageError::SerializationFailed => DataStorageError::SerializationFailed, StorageError::MockDbError => DataStorageError::MockDbError, + StorageError::KafkaError => DataStorageError::KafkaError, StorageError::CustomerRedacted => DataStorageError::CustomerRedacted, StorageError::DeserializationFailed => DataStorageError::DeserializationFailed, StorageError::EncryptionError => DataStorageError::EncryptionError, diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index ee8676106f1..3f892ed9fa7 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -109,6 +109,7 @@ impl PaymentIntentInterface for MockDb { request_incremental_authorization: new.request_incremental_authorization, incremental_authorization_allowed: new.incremental_authorization_allowed, authorization_count: new.authorization_count, + fingerprint_id: new.fingerprint_id, session_expiry: new.session_expiry, }; payment_intents.push(payment_intent.clone()); diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 07d70c9056b..8d20dfe0f32 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -101,6 +101,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { request_incremental_authorization: new.request_incremental_authorization, incremental_authorization_allowed: new.incremental_authorization_allowed, authorization_count: new.authorization_count, + fingerprint_id: new.fingerprint_id.clone(), session_expiry: new.session_expiry, }; let redis_entry = kv::TypedSql { @@ -769,6 +770,7 @@ impl DataModelExt for PaymentIntentNew { request_incremental_authorization: self.request_incremental_authorization, incremental_authorization_allowed: self.incremental_authorization_allowed, authorization_count: self.authorization_count, + fingerprint_id: self.fingerprint_id, session_expiry: self.session_expiry, } } @@ -813,6 +815,7 @@ impl DataModelExt for PaymentIntentNew { request_incremental_authorization: storage_model.request_incremental_authorization, incremental_authorization_allowed: storage_model.incremental_authorization_allowed, authorization_count: storage_model.authorization_count, + fingerprint_id: storage_model.fingerprint_id, session_expiry: storage_model.session_expiry, } } @@ -862,6 +865,7 @@ impl DataModelExt for PaymentIntent { request_incremental_authorization: self.request_incremental_authorization, incremental_authorization_allowed: self.incremental_authorization_allowed, authorization_count: self.authorization_count, + fingerprint_id: self.fingerprint_id, session_expiry: self.session_expiry, } } @@ -907,6 +911,7 @@ impl DataModelExt for PaymentIntent { request_incremental_authorization: storage_model.request_incremental_authorization, incremental_authorization_allowed: storage_model.incremental_authorization_allowed, authorization_count: storage_model.authorization_count, + fingerprint_id: storage_model.fingerprint_id, session_expiry: storage_model.session_expiry, } } @@ -990,6 +995,7 @@ impl DataModelExt for PaymentIntentUpdate { metadata, payment_confirm_source, updated_by, + fingerprint_id, session_expiry, } => DieselPaymentIntentUpdate::Update { amount, @@ -1009,6 +1015,7 @@ impl DataModelExt for PaymentIntentUpdate { metadata, payment_confirm_source, updated_by, + fingerprint_id, session_expiry, }, Self::PaymentAttemptAndAttemptCountUpdate { diff --git a/migrations/2023-12-11-075542_create_pm_fingerprint_table/down.sql b/migrations/2023-12-11-075542_create_pm_fingerprint_table/down.sql new file mode 100644 index 00000000000..74c450622a7 --- /dev/null +++ b/migrations/2023-12-11-075542_create_pm_fingerprint_table/down.sql @@ -0,0 +1,5 @@ +-- This file should undo anything in `up.sql` + +DROP TABLE blocklist_fingerprint; + +DROP TYPE "BlocklistDataKind"; diff --git a/migrations/2023-12-11-075542_create_pm_fingerprint_table/up.sql b/migrations/2023-12-11-075542_create_pm_fingerprint_table/up.sql new file mode 100644 index 00000000000..417d779200f --- /dev/null +++ b/migrations/2023-12-11-075542_create_pm_fingerprint_table/up.sql @@ -0,0 +1,19 @@ +-- Your SQL goes here + +CREATE TYPE "BlocklistDataKind" AS ENUM ( + 'payment_method', + 'card_bin', + 'extended_card_bin' +); + +CREATE TABLE blocklist_fingerprint ( + id SERIAL PRIMARY KEY, + merchant_id VARCHAR(64) NOT NULL, + fingerprint_id VARCHAR(64) NOT NULL, + data_kind "BlocklistDataKind" NOT NULL, + encrypted_fingerprint TEXT NOT NULL, + created_at TIMESTAMP NOT NULL +); + +CREATE UNIQUE INDEX blocklist_fingerprint_merchant_id_fingerprint_id_index +ON blocklist_fingerprint (merchant_id, fingerprint_id); diff --git a/migrations/2023-12-12-112941_create_pm_blocklist_table/down.sql b/migrations/2023-12-12-112941_create_pm_blocklist_table/down.sql new file mode 100644 index 00000000000..cd7d412aad9 --- /dev/null +++ b/migrations/2023-12-12-112941_create_pm_blocklist_table/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +DROP TABLE blocklist; diff --git a/migrations/2023-12-12-112941_create_pm_blocklist_table/up.sql b/migrations/2023-12-12-112941_create_pm_blocklist_table/up.sql new file mode 100644 index 00000000000..6d921dd78c3 --- /dev/null +++ b/migrations/2023-12-12-112941_create_pm_blocklist_table/up.sql @@ -0,0 +1,13 @@ +-- Your SQL goes here + +CREATE TABLE blocklist ( + id SERIAL PRIMARY KEY, + merchant_id VARCHAR(64) NOT NULL, + fingerprint_id VARCHAR(64) NOT NULL, + data_kind "BlocklistDataKind" NOT NULL, + metadata JSONB, + created_at TIMESTAMP NOT NULL +); + +CREATE UNIQUE INDEX blocklist_unique_fingerprint_id_index ON blocklist (merchant_id, fingerprint_id); +CREATE INDEX blocklist_merchant_id_data_kind_created_at_index ON blocklist (merchant_id, data_kind, created_at DESC); diff --git a/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/down.sql b/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/down.sql new file mode 100644 index 00000000000..46b871b6ee4 --- /dev/null +++ b/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent DROP COLUMN IF EXISTS fingerprint_id; diff --git a/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/up.sql b/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/up.sql new file mode 100644 index 00000000000..831fb7b6ffc --- /dev/null +++ b/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS fingerprint_id VARCHAR(64); diff --git a/migrations/2023-12-18-062613_create_blocklist_lookup_table/down.sql b/migrations/2023-12-18-062613_create_blocklist_lookup_table/down.sql new file mode 100644 index 00000000000..d2363f547a5 --- /dev/null +++ b/migrations/2023-12-18-062613_create_blocklist_lookup_table/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +DROP TABLE blocklist_lookup; diff --git a/migrations/2023-12-18-062613_create_blocklist_lookup_table/up.sql b/migrations/2023-12-18-062613_create_blocklist_lookup_table/up.sql new file mode 100644 index 00000000000..8af3e209fc6 --- /dev/null +++ b/migrations/2023-12-18-062613_create_blocklist_lookup_table/up.sql @@ -0,0 +1,9 @@ +-- Your SQL goes here + +CREATE TABLE blocklist_lookup ( + id SERIAL PRIMARY KEY, + merchant_id VARCHAR(64) NOT NULL, + fingerprint TEXT NOT NULL +); + +CREATE UNIQUE INDEX blocklist_lookup_merchant_id_fingerprint_index ON blocklist_lookup (merchant_id, fingerprint); diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index dd27b5d609d..74cfc752c57 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -10744,6 +10744,11 @@ }, "description": "List of incremental authorizations happened to the payment", "nullable": true + }, + "fingerprint": { + "type": "string", + "description": "Payment Fingerprint", + "nullable": true } } },
2023-12-05T11:57:03Z
## 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 feature will allow the merchants to block the following according to their needs: ``` 1. card_numbers 2. card_isins 3. extended_bins ``` ### 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` 5. `crates/router/src/configs` 6. `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). --> Requested by 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)? --> Refer to the attached postman collection for the API contracts for the blocklist APIs. Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin. For Card Bin and Extended Card Bin :- 1. Setup a Merchant Account and any Connector account 2. Make a payment with a certain card (ensure it succeeds) 3. Block the card's card bin or extended card bin 4. Try the payment again (should fail this time with an API response saying that the payment was blocked) For Payment Instrument :- 1. Repeat steps 1 and 2 of previous section 2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card. 3. Try the payment again (should fail) [blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8626bda6d5aa9e7531edc7ea50ed4f30c3b7227a
juspay/hyperswitch
juspay__hyperswitch-3427
Bug: [BUG] Add payout features for euclid_wasm crate ### Bug Description `euclid_wasm` is a dependency of hyperswitch dashboard which includes list of connectors, PMs, and other related structs and enums. This also includes payout related stuff which is enabled under `payouts` feature. However, the feature `payouts` itself is missing from `euclid_wasm` crate. This needs to be added in the crate. ### Expected Behavior To be able to include payout related definitions in `euclid_wasm` in the final target if the feature was enabled. ### Actual Behavior Payout related definitions are not included in wasm target. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index d9f5330a1b8..13296bcde62 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -10,7 +10,7 @@ rust-version.workspace = true crate-type = ["cdylib"] [features] -default = ["connector_choice_bcompat", "connector_choice_mca_id"] +default = ["connector_choice_bcompat","payouts", "connector_choice_mca_id"] release = ["connector_choice_bcompat", "connector_choice_mca_id"] connector_choice_bcompat = ["api_models/connector_choice_bcompat"] connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connector_choice_mca_id", "kgraph_utils/connector_choice_mca_id"] @@ -18,6 +18,7 @@ dummy_connector = ["kgraph_utils/dummy_connector", "connector_configs/dummy_conn production = ["connector_configs/production"] development = ["connector_configs/development"] sandbox = ["connector_configs/sandbox"] +payouts = [] [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" }
2024-01-18T13:59:39Z
## 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 --> ### 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)? --> <img width="1675" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/7d08729a-a8b0-46b7-856d-c5587c795649"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f1fd0b101791f20980e21e8fd8bf10fac3179209
juspay/hyperswitch
juspay__hyperswitch-3449
Bug: [FEATURE] Integrate Stripe Connect for paying out ### Feature Description Stripe Connect platform enables merchants to onboard and pay to their customers, partners, vendors etc. This is to be added as a Payout Connector. ### Possible Implementation Integrate Stripe Connect under Stripe connector integration for payout actions - PoCreate - PoRecipient - PoRecipientAccount - PoFulfill ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 1076cbdc196..b2e1fe3c458 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -487,7 +487,7 @@ debit = { currency = "USD" } [connector_customer] connector_list = "gocardless,stax,stripe" -payout_connector_list = "wise" +payout_connector_list = "stripe,wise" [bank_config.online_banking_fpx] adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" diff --git a/config/development.toml b/config/development.toml index 4062ae6d9e9..92e13f24fec 100644 --- a/config/development.toml +++ b/config/development.toml @@ -474,7 +474,7 @@ payme = { payment_method = "card" } [connector_customer] connector_list = "gocardless,stax,stripe" -payout_connector_list = "wise" +payout_connector_list = "stripe,wise" [dummy_connector] enabled = true diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 27e5878de6d..d99ab473501 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -395,7 +395,7 @@ connector_list = "stripe,adyen,cybersource" [connector_customer] connector_list = "gocardless,stax,stripe" -payout_connector_list = "wise" +payout_connector_list = "stripe,wise" [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 6bdb51281fb..452ad6332fb 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -154,6 +154,10 @@ impl Connector { pub fn supports_access_token_for_payout(&self, payout_method: PayoutType) -> bool { matches!((self, payout_method), (Self::Paypal, _)) } + #[cfg(feature = "payouts")] + pub fn supports_vendor_disburse_account_create_for_payout(&self) -> bool { + matches!(self, Self::Stripe) + } pub fn supports_access_token(&self, payment_method: PaymentMethod) -> bool { matches!( (self, payment_method), @@ -338,6 +342,7 @@ pub enum AuthenticationConnectors { #[strum(serialize_all = "snake_case")] pub enum PayoutConnectors { Adyen, + Stripe, Wise, Paypal, } @@ -347,6 +352,7 @@ impl From<PayoutConnectors> for RoutableConnectors { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, + PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Paypal => Self::Paypal, } @@ -358,6 +364,7 @@ impl From<PayoutConnectors> for Connector { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, + PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Paypal => Self::Paypal, } @@ -370,6 +377,7 @@ impl TryFrom<Connector> for PayoutConnectors { fn try_from(value: Connector) -> Result<Self, Self::Error> { match value { Connector::Adyen => Ok(Self::Adyen), + Connector::Stripe => Ok(Self::Stripe), Connector::Wise => Ok(Self::Wise), Connector::Paypal => Ok(Self::Paypal), _ => Err(format!("Invalid payout connector {}", value)), diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index 4e2d9192554..0951f8c9dfc 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -446,6 +446,7 @@ pub struct PayoutAttemptResponse { #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, + pub merchant_id: Option<String>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] @@ -464,6 +465,9 @@ pub struct PayoutRetrieveRequest { /// (defaults to false) #[schema(value_type = Option<bool>, default = false, example = true)] pub force_sync: Option<bool>, + + /// The identifier for the Merchant Account. + pub merchant_id: Option<String>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] @@ -479,6 +483,43 @@ pub struct PayoutActionRequest { pub payout_id: String, } +#[derive(Default, Debug, ToSchema, Clone, Deserialize)] +pub struct PayoutVendorAccountDetails { + pub vendor_details: PayoutVendorDetails, + pub individual_details: PayoutIndividualDetails, +} + +#[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] +pub struct PayoutVendorDetails { + pub account_type: String, + pub business_type: String, + pub business_profile_mcc: Option<i32>, + pub business_profile_url: Option<String>, + pub business_profile_name: Option<Secret<String>>, + pub company_address_line1: Option<Secret<String>>, + pub company_address_line2: Option<Secret<String>>, + pub company_address_postal_code: Option<Secret<String>>, + pub company_address_city: Option<Secret<String>>, + pub company_address_state: Option<Secret<String>>, + pub company_phone: Option<Secret<String>>, + pub company_tax_id: Option<Secret<String>>, + pub company_owners_provided: Option<bool>, + pub capabilities_card_payments: Option<bool>, + pub capabilities_transfers: Option<bool>, +} + +#[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] +pub struct PayoutIndividualDetails { + pub tos_acceptance_date: Option<i64>, + pub tos_acceptance_ip: Option<Secret<String>>, + pub individual_dob_day: Option<Secret<String>>, + pub individual_dob_month: Option<Secret<String>>, + pub individual_dob_year: Option<Secret<String>>, + pub individual_id_number: Option<Secret<String>>, + pub individual_ssn_last_4: Option<Secret<String>>, + pub external_account_account_holder_type: Option<String>, +} + #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListConstraints { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 0681edbb15a..0cbb1a03d5b 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2113,6 +2113,7 @@ pub enum PayoutStatus { RequiresCreation, RequiresPayoutMethodData, RequiresFulfillment, + RequiresVendorAccountCreation, } #[derive( diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 0b988a195fa..d9d1f18c347 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -28,6 +28,9 @@ pub fn default_payments_list_limit() -> u32 { 10 } +/// Average delay (in seconds) between account onboarding's API response and the changes to actually reflect at Stripe's end +pub const STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS: i64 = 15; + /// Maximum limit for payment link list get api pub const PAYMENTS_LINK_LIST_LIMIT: u32 = 100; diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index d7ae7b8a01e..497accc3346 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -161,6 +161,8 @@ pub struct ConnectorConfig { pub rapyd: Option<ConnectorTomlConfig>, pub shift4: Option<ConnectorTomlConfig>, pub stripe: Option<ConnectorTomlConfig>, + #[cfg(feature = "payouts")] + pub stripe_payout: Option<ConnectorTomlConfig>, pub signifyd: Option<ConnectorTomlConfig>, pub trustpay: Option<ConnectorTomlConfig>, pub threedsecureio: Option<ConnectorTomlConfig>, @@ -214,6 +216,7 @@ impl ConnectorConfig { let connector_data = Self::new()?; match connector { PayoutConnectors::Adyen => Ok(connector_data.adyen_payout), + PayoutConnectors::Stripe => Ok(connector_data.stripe_payout), PayoutConnectors::Wise => Ok(connector_data.wise_payout), PayoutConnectors::Paypal => Ok(connector_data.paypal), } diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 9a231f0dc6d..a81fb3657ab 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -2580,6 +2580,12 @@ api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" key1 = "Adyen Account Id" +[stripe_payout] +[[stripe_payout.bank_transfer]] + payment_method_type = "ach" +[stripe_payout.connector_auth.HeaderKey] +api_key = "Stripe API Key" + [wise_payout] [[wise_payout.bank_transfer]] payment_method_type = "ach" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 5bb61ec2320..1d0fbb71538 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -2582,6 +2582,12 @@ api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" key1 = "Adyen Account Id" +[stripe_payout] +[[stripe_payout.bank_transfer]] + payment_method_type = "ach" +[stripe_payout.connector_auth.HeaderKey] +api_key = "Stripe API Key" + [wise_payout] [[wise_payout.bank_transfer]] payment_method_type = "ach" diff --git a/crates/data_models/src/payouts/payouts.rs b/crates/data_models/src/payouts/payouts.rs index 28a8e4d4278..679e4488f7b 100644 --- a/crates/data_models/src/payouts/payouts.rs +++ b/crates/data_models/src/payouts/payouts.rs @@ -89,6 +89,7 @@ pub struct Payouts { pub attempt_count: i16, pub profile_id: String, pub status: storage_enums::PayoutStatus, + pub confirm: Option<bool>, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -110,9 +111,10 @@ pub struct PayoutsNew { pub metadata: Option<pii::SecretSerdeValue>, pub created_at: Option<PrimitiveDateTime>, pub last_modified_at: Option<PrimitiveDateTime>, + pub attempt_count: i16, pub profile_id: String, pub status: storage_enums::PayoutStatus, - pub attempt_count: i16, + pub confirm: Option<bool>, } impl Default for PayoutsNew { @@ -137,9 +139,10 @@ impl Default for PayoutsNew { metadata: Option::default(), created_at: Some(now), last_modified_at: Some(now), + attempt_count: 1, profile_id: String::default(), status: storage_enums::PayoutStatus::default(), - attempt_count: 1, + confirm: None, } } } @@ -158,6 +161,7 @@ pub enum PayoutsUpdate { metadata: Option<pii::SecretSerdeValue>, profile_id: Option<String>, status: Option<storage_enums::PayoutStatus>, + confirm: Option<bool>, }, PayoutMethodIdUpdate { payout_method_id: String, @@ -188,6 +192,7 @@ pub struct PayoutsUpdateInternal { pub profile_id: Option<String>, pub status: Option<storage_enums::PayoutStatus>, pub attempt_count: Option<i16>, + pub confirm: Option<bool>, } impl From<PayoutsUpdate> for PayoutsUpdateInternal { @@ -205,6 +210,7 @@ impl From<PayoutsUpdate> for PayoutsUpdateInternal { metadata, profile_id, status, + confirm, } => Self { amount: Some(amount), destination_currency: Some(destination_currency), @@ -217,6 +223,7 @@ impl From<PayoutsUpdate> for PayoutsUpdateInternal { metadata, profile_id, status, + confirm, ..Default::default() }, PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self { diff --git a/crates/diesel_models/src/payouts.rs b/crates/diesel_models/src/payouts.rs index 7cc348d445d..4c6fe40c399 100644 --- a/crates/diesel_models/src/payouts.rs +++ b/crates/diesel_models/src/payouts.rs @@ -32,6 +32,7 @@ pub struct Payouts { pub attempt_count: i16, pub profile_id: String, pub status: storage_enums::PayoutStatus, + pub confirm: Option<bool>, } #[derive( @@ -67,9 +68,10 @@ pub struct PayoutsNew { pub created_at: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_modified_at: Option<PrimitiveDateTime>, + pub attempt_count: i16, pub profile_id: String, pub status: storage_enums::PayoutStatus, - pub attempt_count: i16, + pub confirm: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -86,6 +88,7 @@ pub enum PayoutsUpdate { metadata: Option<pii::SecretSerdeValue>, profile_id: Option<String>, status: Option<storage_enums::PayoutStatus>, + confirm: Option<bool>, }, PayoutMethodIdUpdate { payout_method_id: String, @@ -118,6 +121,7 @@ pub struct PayoutsUpdateInternal { pub status: Option<storage_enums::PayoutStatus>, pub last_modified_at: PrimitiveDateTime, pub attempt_count: Option<i16>, + pub confirm: Option<bool>, } impl Default for PayoutsUpdateInternal { @@ -137,6 +141,7 @@ impl Default for PayoutsUpdateInternal { status: None, last_modified_at: common_utils::date_time::now(), attempt_count: None, + confirm: None, } } } @@ -156,6 +161,7 @@ impl From<PayoutsUpdate> for PayoutsUpdateInternal { metadata, profile_id, status, + confirm, } => Self { amount: Some(amount), destination_currency: Some(destination_currency), @@ -168,6 +174,7 @@ impl From<PayoutsUpdate> for PayoutsUpdateInternal { metadata, profile_id, status, + confirm, ..Default::default() }, PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self { @@ -207,6 +214,7 @@ impl PayoutsUpdate { status, last_modified_at, attempt_count, + confirm, } = self.into(); Payouts { amount: amount.unwrap_or(source.amount), @@ -223,6 +231,7 @@ impl PayoutsUpdate { status: status.unwrap_or(source.status), last_modified_at, attempt_count: attempt_count.unwrap_or(source.attempt_count), + confirm: confirm.or(source.confirm), ..source } } diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 0c6aaa5922f..cd0dbed2c64 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -209,6 +209,7 @@ pub enum ProcessTrackerRunner { DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, + AttachPayoutAccountWorkflow, } #[cfg(test)] diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index bbe8a8060fc..ff0539cc05e 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -999,6 +999,7 @@ diesel::table! { #[max_length = 64] profile_id -> Varchar, status -> PayoutStatus, + confirm -> Nullable<Bool>, } } diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 1df37e9f6d1..47f41d8700f 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -263,6 +263,23 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow => Ok(Box::new( workflows::outgoing_webhook_retry::OutgoingWebhookRetryWorkflow, )), + storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow => { + #[cfg(feature = "payouts")] + { + Ok(Box::new( + workflows::attach_payout_account_workflow::AttachPayoutAccountWorkflow, + )) + } + #[cfg(not(feature = "payouts"))] + { + Err( + error_stack::report!(ProcessTrackerError::UnexpectedFlow), + ) + .attach_printable( + "Cannot run Stripe external account workflow when payouts feature is disabled", + ) + } + } } }; diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index d02078702e8..bde04877e65 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -4768,10 +4768,8 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenPayoutResponse>> let status = payout_eligible.map_or( { response.result_code.map_or( - response - .response - .map(storage_enums::PayoutStatus::foreign_from), - |rc| Some(storage_enums::PayoutStatus::foreign_from(rc)), + response.response.map(storage_enums::PayoutStatus::from), + |rc| Some(storage_enums::PayoutStatus::from(rc)), ) }, |pe| { @@ -4788,6 +4786,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenPayoutResponse>> status, connector_payout_id: response.psp_reference, payout_eligible, + should_add_next_step_to_process_tracker: false, }), ..item.data }) @@ -4795,8 +4794,8 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenPayoutResponse>> } #[cfg(feature = "payouts")] -impl ForeignFrom<AdyenStatus> for storage_enums::PayoutStatus { - fn foreign_from(adyen_status: AdyenStatus) -> Self { +impl From<AdyenStatus> for storage_enums::PayoutStatus { + fn from(adyen_status: AdyenStatus) -> Self { match adyen_status { AdyenStatus::Authorised | AdyenStatus::PayoutConfirmReceived => Self::Success, AdyenStatus::Cancelled | AdyenStatus::PayoutDeclineReceived => Self::Cancelled, diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index e499cdda12c..64789e176fc 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -11,6 +11,8 @@ use stripe::auth_headers; use self::transformers as stripe; use super::utils::{self as connector_utils, RefundsRequestData}; +#[cfg(feature = "payouts")] +use super::utils::{PayoutsData, RouterData}; use crate::{ configs::settings, consts, @@ -27,7 +29,7 @@ use crate::{ }, types::{ self, - api::{self, ConnectorCommon}, + api::{self, ConnectorCommon, ConnectorCommonExt}, domain, }, utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, @@ -36,6 +38,25 @@ use crate::{ #[derive(Debug, Clone)] pub struct Stripe; +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Stripe +where + Self: services::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::common_get_content_type(self).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 Stripe { fn id(&self) -> &'static str { "stripe" @@ -67,6 +88,34 @@ impl ConnectorCommon for Stripe { ), ]) } + + #[cfg(feature = "payouts")] + fn build_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: stripe::StripeConnectErrorResponse = res + .response + .parse_struct("StripeConnectErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + Ok(types::ErrorResponse { + status_code: res.status_code, + code: response + .error + .code + .clone() + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: response + .error + .code + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: response.error.message, + attempt_status: None, + connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + }) + } } impl ConnectorValidation for Stripe { @@ -2235,3 +2284,434 @@ impl services::ConnectorRedirectResponse for Stripe { } } } + +impl api::Payouts for Stripe {} +#[cfg(feature = "payouts")] +impl api::PayoutCancel for Stripe {} +#[cfg(feature = "payouts")] +impl api::PayoutCreate for Stripe {} +#[cfg(feature = "payouts")] +impl api::PayoutFulfill for Stripe {} +#[cfg(feature = "payouts")] +impl api::PayoutRecipient for Stripe {} +#[cfg(feature = "payouts")] +impl api::PayoutRecipientAccount for Stripe {} + +#[cfg(feature = "payouts")] +impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> + for Stripe +{ + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PayoutsRouterData<api::PoCancel>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let transfer_id = req.request.get_transfer_id()?; + Ok(format!( + "{}v1/transfers/{}/reversals", + connectors.stripe.base_url, transfer_id + )) + } + + fn get_headers( + &self, + req: &types::PayoutsRouterData<api::PoCancel>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, _connectors) + } + + fn get_request_body( + &self, + req: &types::RouterData<api::PoCancel, types::PayoutsData, types::PayoutsResponseData>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = stripe::StripeConnectReversalRequest::try_from(req)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PayoutsRouterData<api::PoCancel>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PayoutCancelType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) + .set_body(types::PayoutCancelType::get_request_body( + self, req, connectors, + )?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PayoutsRouterData<api::PoCancel>, + event_builder: Option<&mut ConnectorEvent>, + res: types::Response, + ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { + let response: stripe::StripeConnectReversalResponse = res + .response + .parse_struct("StripeConnectReversalResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "payouts")] +impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> + for Stripe +{ + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PayoutsRouterData<api::PoCreate>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}v1/transfers", connectors.stripe.base_url)) + } + + fn get_headers( + &self, + req: &types::PayoutsRouterData<api::PoCreate>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_request_body( + &self, + req: &types::PayoutsRouterData<api::PoCreate>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = stripe::StripeConnectPayoutCreateRequest::try_from(req)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PayoutsRouterData<api::PoCreate>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PayoutCreateType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) + .set_body(types::PayoutCreateType::get_request_body( + self, req, connectors, + )?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PayoutsRouterData<api::PoCreate>, + event_builder: Option<&mut ConnectorEvent>, + res: types::Response, + ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { + let response: stripe::StripeConnectPayoutCreateResponse = res + .response + .parse_struct("StripeConnectPayoutCreateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "payouts")] +impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> + for Stripe +{ + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PayoutsRouterData<api::PoFulfill>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}v1/payouts", connectors.stripe.base_url,)) + } + + fn get_headers( + &self, + req: &types::PayoutsRouterData<api::PoFulfill>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let mut headers = self.build_headers(req, connectors)?; + let customer_account = req.get_connector_customer_id()?; + let mut customer_account_header = vec![( + headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + customer_account.into_masked(), + )]; + headers.append(&mut customer_account_header); + Ok(headers) + } + + fn get_request_body( + &self, + req: &types::PayoutsRouterData<api::PoFulfill>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = stripe::StripeConnectPayoutFulfillRequest::try_from(req)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PayoutsRouterData<api::PoFulfill>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PayoutFulfillType::get_headers( + self, req, connectors, + )?) + .set_body(types::PayoutFulfillType::get_request_body( + self, req, connectors, + )?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PayoutsRouterData<api::PoFulfill>, + event_builder: Option<&mut ConnectorEvent>, + res: types::Response, + ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { + let response: stripe::StripeConnectPayoutFulfillResponse = res + .response + .parse_struct("StripeConnectPayoutFulfillResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "payouts")] +impl + services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> + for Stripe +{ + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PayoutsRouterData<api::PoRecipient>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}v1/accounts", connectors.stripe.base_url)) + } + + fn get_headers( + &self, + req: &types::PayoutsRouterData<api::PoRecipient>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_request_body( + &self, + req: &types::PayoutsRouterData<api::PoRecipient>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = stripe::StripeConnectRecipientCreateRequest::try_from(req)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PayoutsRouterData<api::PoRecipient>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PayoutRecipientType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PayoutRecipientType::get_headers( + self, req, connectors, + )?) + .set_body(types::PayoutRecipientType::get_request_body( + self, req, connectors, + )?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PayoutsRouterData<api::PoRecipient>, + event_builder: Option<&mut ConnectorEvent>, + res: types::Response, + ) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> { + let response: stripe::StripeConnectRecipientCreateResponse = res + .response + .parse_struct("StripeConnectRecipientCreateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "payouts")] +impl + services::ConnectorIntegration< + api::PoRecipientAccount, + types::PayoutsData, + types::PayoutsResponseData, + > for Stripe +{ + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PayoutsRouterData<api::PoRecipientAccount>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_customer_id = req.get_connector_customer_id()?; + Ok(format!( + "{}v1/accounts/{}/external_accounts", + connectors.stripe.base_url, connector_customer_id + )) + } + + fn get_headers( + &self, + req: &types::PayoutsRouterData<api::PoRecipientAccount>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_request_body( + &self, + req: &types::PayoutsRouterData<api::PoRecipientAccount>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PayoutsRouterData<api::PoRecipientAccount>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PayoutRecipientAccountType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PayoutRecipientAccountType::get_headers( + self, req, connectors, + )?) + .set_body(types::PayoutRecipientAccountType::get_request_body( + self, req, connectors, + )?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PayoutsRouterData<api::PoRecipientAccount>, + event_builder: Option<&mut ConnectorEvent>, + res: types::Response, + ) -> CustomResult<types::PayoutsRouterData<api::PoRecipientAccount>, errors::ConnectorError> + { + let response: stripe::StripeConnectRecipientAccountCreateResponse = res + .response + .parse_struct("StripeConnectRecipientAccountCreateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index e0801eea284..c561b26bcfd 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -15,6 +15,10 @@ use serde_json::Value; use time::PrimitiveDateTime; use url::Url; +#[cfg(feature = "payouts")] +pub mod connect; +#[cfg(feature = "payouts")] +pub use self::connect::*; use crate::{ collect_missing_value_keys, connector::utils::{ diff --git a/crates/router/src/connector/stripe/transformers/connect.rs b/crates/router/src/connector/stripe/transformers/connect.rs new file mode 100644 index 00000000000..df4376b7174 --- /dev/null +++ b/crates/router/src/connector/stripe/transformers/connect.rs @@ -0,0 +1,475 @@ +use api_models; +use common_utils::pii::Email; +use error_stack::ResultExt; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use super::ErrorDetails; +use crate::{ + connector::utils::{PayoutsData, RouterData}, + core::{errors, payments::CustomerDetailsExt}, + types::{self, storage::enums, PayoutIndividualDetailsExt}, + utils::OptionExt, +}; + +type Error = error_stack::Report<errors::ConnectorError>; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum StripeConnectPayoutStatus { + Canceled, + Failed, + InTransit, + Paid, + Pending, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct StripeConnectErrorResponse { + pub error: ErrorDetails, +} + +// Payouts +#[derive(Clone, Debug, Serialize)] +pub struct StripeConnectPayoutCreateRequest { + amount: i64, + currency: enums::Currency, + destination: String, + transfer_group: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct StripeConnectPayoutCreateResponse { + id: String, + description: Option<String>, + source_transaction: Option<String>, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct TransferReversals { + object: String, + has_more: bool, + total_count: i32, + url: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct StripeConnectPayoutFulfillRequest { + amount: i64, + currency: enums::Currency, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct StripeConnectPayoutFulfillResponse { + id: String, + currency: String, + description: Option<String>, + failure_balance_transaction: Option<String>, + failure_code: Option<String>, + failure_message: Option<String>, + original_payout: Option<String>, + reversed_by: Option<String>, + statement_descriptor: Option<String>, + status: StripeConnectPayoutStatus, +} + +#[derive(Clone, Debug, Serialize)] +pub struct StripeConnectReversalRequest { + amount: i64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct StripeConnectReversalResponse { + id: String, + source_refund: Option<String>, +} + +#[derive(Clone, Debug, Serialize)] +pub struct StripeConnectRecipientCreateRequest { + #[serde(rename = "type")] + account_type: String, + country: Option<enums::CountryAlpha2>, + email: Option<Email>, + #[serde(rename = "capabilities[card_payments][requested]")] + capabilities_card_payments: Option<bool>, + #[serde(rename = "capabilities[transfers][requested]")] + capabilities_transfers: Option<bool>, + #[serde(rename = "tos_acceptance[date]")] + tos_acceptance_date: Option<i64>, + #[serde(rename = "tos_acceptance[ip]")] + tos_acceptance_ip: Option<Secret<String>>, + business_type: String, + #[serde(rename = "business_profile[mcc]")] + business_profile_mcc: Option<i32>, + #[serde(rename = "business_profile[url]")] + business_profile_url: Option<String>, + #[serde(rename = "business_profile[name]")] + business_profile_name: Option<Secret<String>>, + #[serde(rename = "company[name]")] + company_name: Option<Secret<String>>, + #[serde(rename = "company[address][line1]")] + company_address_line1: Option<Secret<String>>, + #[serde(rename = "company[address][line2]")] + company_address_line2: Option<Secret<String>>, + #[serde(rename = "company[address][postal_code]")] + company_address_postal_code: Option<Secret<String>>, + #[serde(rename = "company[address][city]")] + company_address_city: Option<Secret<String>>, + #[serde(rename = "company[address][state]")] + company_address_state: Option<Secret<String>>, + #[serde(rename = "company[phone]")] + company_phone: Option<Secret<String>>, + #[serde(rename = "company[tax_id]")] + company_tax_id: Option<Secret<String>>, + #[serde(rename = "company[owners_provided]")] + company_owners_provided: Option<bool>, + #[serde(rename = "individual[first_name]")] + individual_first_name: Option<Secret<String>>, + #[serde(rename = "individual[last_name]")] + individual_last_name: Option<Secret<String>>, + #[serde(rename = "individual[dob][day]")] + individual_dob_day: Option<Secret<String>>, + #[serde(rename = "individual[dob][month]")] + individual_dob_month: Option<Secret<String>>, + #[serde(rename = "individual[dob][year]")] + individual_dob_year: Option<Secret<String>>, + #[serde(rename = "individual[address][line1]")] + individual_address_line1: Option<Secret<String>>, + #[serde(rename = "individual[address][line2]")] + individual_address_line2: Option<Secret<String>>, + #[serde(rename = "individual[address][postal_code]")] + individual_address_postal_code: Option<Secret<String>>, + #[serde(rename = "individual[address][city]")] + individual_address_city: Option<String>, + #[serde(rename = "individual[address][state]")] + individual_address_state: Option<Secret<String>>, + #[serde(rename = "individual[email]")] + individual_email: Option<Email>, + #[serde(rename = "individual[phone]")] + individual_phone: Option<Secret<String>>, + #[serde(rename = "individual[id_number]")] + individual_id_number: Option<Secret<String>>, + #[serde(rename = "individual[ssn_last_4]")] + individual_ssn_last_4: Option<Secret<String>>, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct StripeConnectRecipientCreateResponse { + id: String, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(untagged)] +pub enum StripeConnectRecipientAccountCreateRequest { + Bank(RecipientBankAccountRequest), + Card(RecipientCardAccountRequest), + Token(RecipientTokenRequest), +} + +#[derive(Clone, Debug, Serialize)] +pub struct RecipientTokenRequest { + external_account: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct RecipientCardAccountRequest { + #[serde(rename = "external_account[object]")] + external_account_object: String, + #[serde(rename = "external_account[number]")] + external_account_number: Secret<String>, + #[serde(rename = "external_account[exp_month]")] + external_account_exp_month: Secret<String>, + #[serde(rename = "external_account[exp_year]")] + external_account_exp_year: Secret<String>, +} + +#[derive(Clone, Debug, Serialize)] +pub struct RecipientBankAccountRequest { + #[serde(rename = "external_account[object]")] + external_account_object: String, + #[serde(rename = "external_account[country]")] + external_account_country: enums::CountryAlpha2, + #[serde(rename = "external_account[currency]")] + external_account_currency: enums::Currency, + #[serde(rename = "external_account[account_holder_name]")] + external_account_account_holder_name: Secret<String>, + #[serde(rename = "external_account[account_number]")] + external_account_account_number: Secret<String>, + #[serde(rename = "external_account[account_holder_type]")] + external_account_account_holder_type: String, + #[serde(rename = "external_account[routing_number]")] + external_account_routing_number: Secret<String>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct StripeConnectRecipientAccountCreateResponse { + id: String, +} + +// Payouts create/transfer request transform +impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectPayoutCreateRequest { + type Error = Error; + fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + let request = item.request.to_owned(); + let connector_customer_id = item.get_connector_customer_id()?; + Ok(Self { + amount: request.amount, + currency: request.destination_currency, + destination: connector_customer_id, + transfer_group: request.payout_id, + }) + } +} + +// Payouts create response transform +impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>> + for types::PayoutsRouterData<F> +{ + type Error = Error; + fn try_from( + item: types::PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>, + ) -> Result<Self, Self::Error> { + let response: StripeConnectPayoutCreateResponse = item.response; + + Ok(Self { + response: Ok(types::PayoutsResponseData { + status: Some(enums::PayoutStatus::RequiresFulfillment), + connector_payout_id: response.id, + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + }), + ..item.data + }) + } +} + +// Payouts fulfill request transform +impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequest { + type Error = Error; + fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + let request = item.request.to_owned(); + Ok(Self { + amount: request.amount, + currency: request.destination_currency, + }) + } +} + +// Payouts fulfill response transform +impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>> + for types::PayoutsRouterData<F> +{ + type Error = Error; + fn try_from( + item: types::PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>, + ) -> Result<Self, Self::Error> { + let response: StripeConnectPayoutFulfillResponse = item.response; + + Ok(Self { + response: Ok(types::PayoutsResponseData { + status: Some(enums::PayoutStatus::from(response.status)), + connector_payout_id: response.id, + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + }), + ..item.data + }) + } +} + +// Payouts reversal request transform +impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectReversalRequest { + type Error = Error; + fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.request.amount, + }) + } +} + +// Payouts reversal response transform +impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectReversalResponse>> + for types::PayoutsRouterData<F> +{ + type Error = Error; + fn try_from( + item: types::PayoutsResponseRouterData<F, StripeConnectReversalResponse>, + ) -> Result<Self, Self::Error> { + let response: StripeConnectReversalResponse = item.response; + + Ok(Self { + response: Ok(types::PayoutsResponseData { + status: Some(enums::PayoutStatus::Cancelled), + connector_payout_id: response.id, + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + }), + ..item.data + }) + } +} + +// Recipient creation request transform +impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientCreateRequest { + type Error = Error; + fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + let request = item.request.to_owned(); + let customer_details = request.get_customer_details()?; + let customer_email = customer_details.get_email()?; + let address = item.get_billing_address()?.clone(); + let payout_vendor_details = request.get_vendor_details()?; + let (vendor_details, individual_details) = ( + payout_vendor_details.vendor_details, + payout_vendor_details.individual_details, + ); + Ok(Self { + account_type: vendor_details.account_type, + country: address.country, + email: Some(customer_email.clone()), + capabilities_card_payments: vendor_details.capabilities_card_payments, + capabilities_transfers: vendor_details.capabilities_transfers, + tos_acceptance_date: individual_details.tos_acceptance_date, + tos_acceptance_ip: individual_details.tos_acceptance_ip, + business_type: vendor_details.business_type, + business_profile_mcc: vendor_details.business_profile_mcc, + business_profile_url: vendor_details.business_profile_url, + business_profile_name: vendor_details.business_profile_name.clone(), + company_name: vendor_details.business_profile_name, + company_address_line1: vendor_details.company_address_line1, + company_address_line2: vendor_details.company_address_line2, + company_address_postal_code: vendor_details.company_address_postal_code, + company_address_city: vendor_details.company_address_city, + company_address_state: vendor_details.company_address_state, + company_phone: vendor_details.company_phone, + company_tax_id: vendor_details.company_tax_id, + company_owners_provided: vendor_details.company_owners_provided, + individual_first_name: address.first_name, + individual_last_name: address.last_name, + individual_dob_day: individual_details.individual_dob_day, + individual_dob_month: individual_details.individual_dob_month, + individual_dob_year: individual_details.individual_dob_year, + individual_address_line1: address.line1, + individual_address_line2: address.line2, + individual_address_postal_code: address.zip, + individual_address_city: address.city, + individual_address_state: address.state, + individual_email: Some(customer_email), + individual_phone: customer_details.phone, + individual_id_number: individual_details.individual_id_number, + individual_ssn_last_4: individual_details.individual_ssn_last_4, + }) + } +} + +// Recipient creation response transform +impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>> + for types::PayoutsRouterData<F> +{ + type Error = Error; + fn try_from( + item: types::PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>, + ) -> Result<Self, Self::Error> { + let response: StripeConnectRecipientCreateResponse = item.response; + + Ok(Self { + response: Ok(types::PayoutsResponseData { + status: Some(enums::PayoutStatus::RequiresVendorAccountCreation), + connector_payout_id: response.id, + payout_eligible: None, + should_add_next_step_to_process_tracker: true, + }), + ..item.data + }) + } +} + +// Recipient account's creation request +impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRequest { + type Error = Error; + fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + let request = item.request.to_owned(); + let payout_method_data = item.get_payout_method_data()?; + let customer_details = request.get_customer_details()?; + let customer_name = customer_details.get_name()?; + let payout_vendor_details = request.get_vendor_details()?; + match payout_method_data { + api_models::payouts::PayoutMethodData::Card(_) => { + Ok(Self::Token(RecipientTokenRequest { + external_account: "tok_visa_debit".to_string(), + })) + } + api_models::payouts::PayoutMethodData::Bank(bank) => match bank { + api_models::payouts::Bank::Ach(bank_details) => { + Ok(Self::Bank(RecipientBankAccountRequest { + external_account_object: "bank_account".to_string(), + external_account_country: bank_details + .bank_country_code + .get_required_value("bank_country_code") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "bank_country_code", + })?, + external_account_currency: request.destination_currency.to_owned(), + external_account_account_holder_name: customer_name, + external_account_account_holder_type: payout_vendor_details + .individual_details + .get_external_account_account_holder_type()?, + external_account_account_number: bank_details.bank_account_number, + external_account_routing_number: bank_details.bank_routing_number, + })) + } + api_models::payouts::Bank::Bacs(_) => Err(errors::ConnectorError::NotSupported { + message: "BACS payouts are not supported".to_string(), + connector: "stripe", + } + .into()), + api_models::payouts::Bank::Sepa(_) => Err(errors::ConnectorError::NotSupported { + message: "SEPA payouts are not supported".to_string(), + connector: "stripe", + } + .into()), + }, + api_models::payouts::PayoutMethodData::Wallet(_) => { + Err(errors::ConnectorError::NotSupported { + message: "Payouts via wallets are not supported".to_string(), + connector: "stripe", + } + .into()) + } + } + } +} + +// Recipient account's creation response +impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>> + for types::PayoutsRouterData<F> +{ + type Error = Error; + fn try_from( + item: types::PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>, + ) -> Result<Self, Self::Error> { + let response: StripeConnectRecipientAccountCreateResponse = item.response; + + Ok(Self { + response: Ok(types::PayoutsResponseData { + status: Some(enums::PayoutStatus::RequiresCreation), + connector_payout_id: response.id, + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + }), + ..item.data + }) + } +} + +impl From<StripeConnectPayoutStatus> for enums::PayoutStatus { + fn from(stripe_connect_status: StripeConnectPayoutStatus) -> Self { + match stripe_connect_status { + StripeConnectPayoutStatus::Paid => Self::Success, + StripeConnectPayoutStatus::Failed => Self::Failed, + StripeConnectPayoutStatus::Canceled => Self::Cancelled, + StripeConnectPayoutStatus::Pending | StripeConnectPayoutStatus::InTransit => { + Self::Pending + } + } + } +} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 6d427c54198..aa4307661e7 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +#[cfg(feature = "payouts")] +use api_models::payouts::PayoutVendorAccountDetails; use api_models::{ enums::{CanadaStatesAbbreviation, UsStatesAbbreviation}, payments::{self, OrderDetailsWithAmount}, @@ -18,6 +20,8 @@ use once_cell::sync::Lazy; use regex::Regex; use serde::Serializer; use time::PrimitiveDateTime; +#[cfg(feature = "payouts")] +use types::CustomerDetails; #[cfg(feature = "frm")] use crate::types::{fraud_check, storage::enums as storage_enums}; @@ -898,6 +902,32 @@ impl RefundsRequestData for types::RefundsData { } } +#[cfg(feature = "payouts")] +pub trait PayoutsData { + fn get_transfer_id(&self) -> Result<String, Error>; + fn get_customer_details(&self) -> Result<CustomerDetails, Error>; + fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>; +} + +#[cfg(feature = "payouts")] +impl PayoutsData for types::PayoutsData { + fn get_transfer_id(&self) -> Result<String, Error> { + self.connector_payout_id + .clone() + .ok_or_else(missing_field_err("transfer_id")) + } + fn get_customer_details(&self) -> Result<CustomerDetails, Error> { + self.customer_details + .clone() + .ok_or_else(missing_field_err("customer_details")) + } + fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> { + self.vendor_details + .clone() + .ok_or_else(missing_field_err("vendor_details")) + } +} + #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayWalletData { diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs index 5416db2d439..c3347fd9387 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/router/src/connector/wise/transformers.rs @@ -13,7 +13,6 @@ use crate::{ types::{ api::payouts, storage::enums::{self as storage_enums, PayoutEntityType}, - transformers::ForeignFrom, }, }; use crate::{core::errors, types}; @@ -320,7 +319,7 @@ fn get_payout_bank_details( }?; match payout_method_data { PayoutMethodData::Bank(payouts::BankPayout::Ach(b)) => Ok(WiseBankDetails { - legal_type: LegalType::foreign_from(entity_type), + legal_type: LegalType::from(entity_type), address: Some(wise_address_details), account_number: Some(b.bank_account_number.to_owned()), abartn: Some(b.bank_routing_number), @@ -328,14 +327,14 @@ fn get_payout_bank_details( ..WiseBankDetails::default() }), PayoutMethodData::Bank(payouts::BankPayout::Bacs(b)) => Ok(WiseBankDetails { - legal_type: LegalType::foreign_from(entity_type), + legal_type: LegalType::from(entity_type), address: Some(wise_address_details), account_number: Some(b.bank_account_number.to_owned()), sort_code: Some(b.bank_sort_code), ..WiseBankDetails::default() }), PayoutMethodData::Bank(payouts::BankPayout::Sepa(b)) => Ok(WiseBankDetails { - legal_type: LegalType::foreign_from(entity_type), + legal_type: LegalType::from(entity_type), address: Some(wise_address_details), iban: Some(b.iban.to_owned()), bic: b.bic, @@ -409,6 +408,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse> status: Some(storage_enums::PayoutStatus::RequiresCreation), connector_payout_id: response.id.to_string(), payout_eligible: None, + should_add_next_step_to_process_tracker: false, }), ..item.data }) @@ -454,6 +454,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>> status: Some(storage_enums::PayoutStatus::RequiresCreation), connector_payout_id: response.id, payout_eligible: None, + should_add_next_step_to_process_tracker: false, }), ..item.data }) @@ -506,7 +507,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutResponse>> item: types::PayoutsResponseRouterData<F, WisePayoutResponse>, ) -> Result<Self, Self::Error> { let response: WisePayoutResponse = item.response; - let status = match storage_enums::PayoutStatus::foreign_from(response.status) { + let status = match storage_enums::PayoutStatus::from(response.status) { storage_enums::PayoutStatus::Cancelled => storage_enums::PayoutStatus::Cancelled, _ => storage_enums::PayoutStatus::RequiresFulfillment, }; @@ -516,6 +517,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutResponse>> status: Some(status), connector_payout_id: response.id.to_string(), payout_eligible: None, + should_add_next_step_to_process_tracker: false, }), ..item.data }) @@ -554,9 +556,10 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseFulfillResponse>> Ok(Self { response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::foreign_from(response.status)), + status: Some(storage_enums::PayoutStatus::from(response.status)), connector_payout_id: "".to_string(), payout_eligible: None, + should_add_next_step_to_process_tracker: false, }), ..item.data }) @@ -564,8 +567,8 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseFulfillResponse>> } #[cfg(feature = "payouts")] -impl ForeignFrom<WiseStatus> for storage_enums::PayoutStatus { - fn foreign_from(wise_status: WiseStatus) -> Self { +impl From<WiseStatus> for storage_enums::PayoutStatus { + fn from(wise_status: WiseStatus) -> Self { match wise_status { WiseStatus::Completed => Self::Success, WiseStatus::Rejected => Self::Failed, @@ -578,8 +581,8 @@ impl ForeignFrom<WiseStatus> for storage_enums::PayoutStatus { } #[cfg(feature = "payouts")] -impl ForeignFrom<PayoutEntityType> for LegalType { - fn foreign_from(entity_type: PayoutEntityType) -> Self { +impl From<PayoutEntityType> for LegalType { + fn from(entity_type: PayoutEntityType) -> Self { match entity_type { PayoutEntityType::Individual | PayoutEntityType::Personal diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 2eb080f952c..b3828e441d6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -59,6 +59,7 @@ use super::{ use crate::core::fraud_check as frm_core; use crate::{ configs::settings::{ApplePayPreDecryptFlow, PaymentMethodTypeTokenFilter}, + connector::utils::missing_field_err, core::{ authentication as authentication_core, errors::{self, CustomResult, RouterResponse, RouterResult}, @@ -2549,6 +2550,22 @@ pub struct CustomerDetails { pub phone_country_code: Option<String>, } +pub trait CustomerDetailsExt { + type Error; + fn get_name(&self) -> Result<Secret<String, masking::WithType>, Self::Error>; + fn get_email(&self) -> Result<pii::Email, Self::Error>; +} + +impl CustomerDetailsExt for CustomerDetails { + type Error = error_stack::Report<errors::ConnectorError>; + fn get_name(&self) -> Result<Secret<String, masking::WithType>, Self::Error> { + self.name.clone().ok_or_else(missing_field_err("name")) + } + fn get_email(&self) -> Result<pii::Email, Self::Error> { + self.email.clone().ok_or_else(missing_field_err("email")) + } +} + pub fn if_not_create_change_operation<'a, Op, F, Ctx>( status: storage_enums::IntentStatus, confirm: Option<bool>, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 59c0b687d64..e2c17a37d92 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -1008,7 +1008,6 @@ default_imp_for_payouts!( connector::Signifyd, connector::Square, connector::Stax, - connector::Stripe, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1095,7 +1094,6 @@ default_imp_for_payouts_create!( connector::Signifyd, connector::Square, connector::Stax, - connector::Stripe, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1272,7 +1270,6 @@ default_imp_for_payouts_fulfill!( connector::Signifyd, connector::Square, connector::Stax, - connector::Stripe, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1359,7 +1356,6 @@ default_imp_for_payouts_cancel!( connector::Signifyd, connector::Square, connector::Stax, - connector::Stripe, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1535,7 +1531,6 @@ default_imp_for_payouts_recipient!( connector::Signifyd, connector::Square, connector::Stax, - connector::Stripe, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1547,6 +1542,97 @@ default_imp_for_payouts_recipient!( connector::Zsl ); +#[cfg(feature = "payouts")] +macro_rules! default_imp_for_payouts_recipient_account { + ($($path:ident::$connector:ident),*) => { + $( + impl api::PayoutRecipientAccount for $path::$connector {} + impl + services::ConnectorIntegration< + api::PoRecipientAccount, + types::PayoutsData, + types::PayoutsResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::PayoutRecipientAccount for connector::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::PoRecipientAccount, + types::PayoutsData, + types::PayoutsResponseData, + > for connector::DummyConnector<T> +{ +} + +#[cfg(feature = "payouts")] +default_imp_for_payouts_recipient_account!( + connector::Aci, + connector::Adyen, + connector::Airwallex, + connector::Authorizedotnet, + connector::Bambora, + connector::Bankofamerica, + connector::Billwerk, + connector::Bitpay, + connector::Bluesnap, + connector::Boku, + connector::Braintree, + connector::Cashtocode, + connector::Checkout, + connector::Cryptopay, + connector::Cybersource, + connector::Coinbase, + connector::Dlocal, + connector::Ebanx, + connector::Fiserv, + connector::Forte, + connector::Globalpay, + connector::Globepay, + connector::Gocardless, + connector::Helcim, + connector::Iatapay, + connector::Klarna, + connector::Mollie, + connector::Multisafepay, + connector::Netcetera, + connector::Nexinets, + connector::Nmi, + connector::Noon, + connector::Nuvei, + connector::Opayo, + connector::Opennode, + connector::Payeezy, + connector::Payme, + connector::Paypal, + connector::Payu, + connector::Placetopay, + connector::Powertranz, + connector::Prophetpay, + connector::Rapyd, + connector::Riskified, + connector::Signifyd, + connector::Square, + connector::Stax, + connector::Shift4, + connector::Threedsecureio, + connector::Trustpay, + connector::Tsys, + connector::Volt, + connector::Wise, + connector::Worldline, + connector::Worldpay, + connector::Zen, + connector::Zsl +); + macro_rules! default_imp_for_approve { ($($path:ident::$connector:ident),*) => { $( diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 1d791e78677..bdaa0c01a10 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -3,31 +3,37 @@ pub mod helpers; #[cfg(feature = "payout_retry")] pub mod retry; pub mod validator; - use std::vec::IntoIter; use api_models::enums as api_enums; -use common_utils::{crypto::Encryptable, ext_traits::ValueExt, pii}; +use common_utils::{consts, crypto::Encryptable, ext_traits::ValueExt, pii}; #[cfg(feature = "olap")] use data_models::errors::StorageError; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; #[cfg(feature = "olap")] use futures::future::join_all; +#[cfg(feature = "payout_retry")] +use retry::GsmValidation; #[cfg(feature = "olap")] use router_env::logger; use router_env::{instrument, tracing}; +use scheduler::utils as pt_utils; use serde_json; -use super::errors::{ConnectorErrorExt, StorageErrorExt}; +use super::{ + errors::{ConnectorErrorExt, StorageErrorExt}, + payments::customers, +}; #[cfg(feature = "olap")] use crate::types::{domain::behaviour::Conversion, transformers::ForeignFrom}; use crate::{ core::{ - errors::{self, RouterResponse, RouterResult}, + errors::{self, CustomResult, RouterResponse, RouterResult}, payments::{self, helpers as payment_helpers}, utils as core_utils, }, + db::StorageInterface, routes::AppState, services, types::{ @@ -50,6 +56,7 @@ pub struct PayoutData { pub payout_attempt: storage::PayoutAttempt, pub payout_method_data: Option<payouts::PayoutMethodData>, pub profile_id: String, + pub should_terminate: bool, } // ********************************************** CORE FLOWS ********************************************** @@ -143,23 +150,20 @@ pub async fn get_connector_choice( } } -#[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn make_connector_decision( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutCreateRequest, connector_call_type: api::ConnectorCallType, - mut payout_data: PayoutData, -) -> RouterResult<PayoutData> { + payout_data: &mut PayoutData, +) -> RouterResult<()> { match connector_call_type { api::ConnectorCallType::PreDetermined(connector_data) => { - payout_data = call_connector_payout( + call_connector_payout( state, merchant_account, key_store, - req, &connector_data, payout_data, ) @@ -167,7 +171,6 @@ pub async fn make_connector_decision( #[cfg(feature = "payout_retry")] { - use crate::core::payouts::retry::GsmValidation; let config_bool = retry::config_should_call_gsm_payout( &*state.store, &merchant_account.merchant_id, @@ -176,30 +179,28 @@ pub async fn make_connector_decision( .await; if config_bool && payout_data.should_call_gsm() { - payout_data = Box::pin(retry::do_gsm_single_connector_actions( + Box::pin(retry::do_gsm_single_connector_actions( state, connector_data, payout_data, merchant_account, key_store, - req, )) .await?; } } - Ok(payout_data) + Ok(()) } api::ConnectorCallType::Retryable(connectors) => { let mut connectors = connectors.into_iter(); let connector_data = get_next_connector(&mut connectors)?; - payout_data = call_connector_payout( + call_connector_payout( state, merchant_account, key_store, - req, &connector_data, payout_data, ) @@ -207,7 +208,6 @@ pub async fn make_connector_decision( #[cfg(feature = "payout_retry")] { - use crate::core::payouts::retry::GsmValidation; let config_multiple_connector_bool = retry::config_should_call_gsm_payout( &*state.store, &merchant_account.merchant_id, @@ -216,14 +216,13 @@ pub async fn make_connector_decision( .await; if config_multiple_connector_bool && payout_data.should_call_gsm() { - payout_data = Box::pin(retry::do_gsm_multiple_connector_actions( + Box::pin(retry::do_gsm_multiple_connector_actions( state, connectors, connector_data.clone(), payout_data, merchant_account, key_store, - req, )) .await?; } @@ -236,24 +235,57 @@ pub async fn make_connector_decision( .await; if config_single_connector_bool && payout_data.should_call_gsm() { - payout_data = Box::pin(retry::do_gsm_single_connector_actions( + Box::pin(retry::do_gsm_single_connector_actions( state, connector_data, payout_data, merchant_account, key_store, - req, )) .await?; } } - Ok(payout_data) + Ok(()) } _ => Err(errors::ApiErrorResponse::InternalServerError)?, } } +#[instrument(skip_all)] +pub async fn payouts_core( + state: &AppState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payout_data: &mut PayoutData, + routing_algorithm: Option<serde_json::Value>, + eligible_connectors: Option<Vec<api_models::enums::PayoutConnectors>>, +) -> RouterResult<()> { + let payout_attempt = &payout_data.payout_attempt; + + // Form connector data + let connector_call_type = get_connector_choice( + state, + merchant_account, + key_store, + payout_attempt.connector.clone(), + routing_algorithm, + payout_data, + eligible_connectors, + ) + .await?; + + // Call connector steps + Box::pin(make_connector_decision( + state, + merchant_account, + key_store, + connector_call_type, + payout_data, + )) + .await +} + #[instrument(skip_all)] pub async fn payouts_create_core( state: AppState, @@ -277,34 +309,33 @@ pub async fn payouts_create_core( ) .await?; - let connector_call_type = get_connector_choice( + let payout_attempt = payout_data.payout_attempt.to_owned(); + + // Persist payout method data in temp locker + payout_data.payout_method_data = helpers::make_payout_method_data( &state, - &merchant_account, + req.payout_method_data.as_ref(), + payout_attempt.payout_token.as_deref(), + &payout_attempt.customer_id, + &payout_attempt.merchant_id, + Some(&payout_data.payouts.payout_type.clone()), &key_store, - None, - req.routing.clone(), - &mut payout_data, - req.connector.clone(), + Some(&mut payout_data), + merchant_account.storage_scheme, ) .await?; - payout_data = Box::pin(make_connector_decision( + payouts_core( &state, &merchant_account, &key_store, - &req, - connector_call_type, - payout_data, - )) + &mut payout_data, + req.routing.clone(), + req.connector.clone(), + ) .await?; - response_handler( - &state, - &merchant_account, - &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), - &payout_data, - ) - .await + response_handler(&merchant_account, &payout_data).await } pub async fn payouts_update_core( @@ -349,6 +380,7 @@ pub async fn payouts_update_core( metadata: req.metadata.clone().or(payouts.metadata.clone()), status: Some(status), profile_id: Some(payout_attempt.profile_id.clone()), + confirm: req.confirm, }; let db = &*state.store; @@ -400,61 +432,39 @@ pub async fn payouts_update_core( } } - if ( - req.connector.is_none(), - payout_data.payout_attempt.connector.is_some(), - ) != (true, true) - { + let payout_attempt = payout_data.payout_attempt.to_owned(); + + if (req.connector.is_none(), payout_attempt.connector.is_some()) != (true, true) { // if the connector is not updated but was provided during payout create payout_data.payout_attempt.connector = None; payout_data.payout_attempt.routing_info = None; - - //fetch payout_method_data - payout_data.payout_method_data = Some( - helpers::make_payout_method_data( - &state, - req.payout_method_data.as_ref(), - payout_data.payout_attempt.payout_token.clone().as_deref(), - &payout_data.payout_attempt.customer_id.clone(), - &payout_data.payout_attempt.merchant_id.clone(), - Some(&payouts.payout_type), - &key_store, - Some(&mut payout_data), - merchant_account.storage_scheme, - ) - .await? - .get_required_value("payout_method_data")?, - ); }; - let connector_call_type = get_connector_choice( + // Update payout method data in temp locker + payout_data.payout_method_data = helpers::make_payout_method_data( &state, - &merchant_account, + req.payout_method_data.as_ref(), + payout_attempt.payout_token.as_deref(), + &payout_attempt.customer_id, + &payout_attempt.merchant_id, + Some(&payout_data.payouts.payout_type.clone()), &key_store, - None, - req.routing.clone(), - &mut payout_data, - req.connector.clone(), + Some(&mut payout_data), + merchant_account.storage_scheme, ) .await?; - payout_data = Box::pin(make_connector_decision( + payouts_core( &state, &merchant_account, &key_store, - &req, - connector_call_type, - payout_data, - )) + &mut payout_data, + req.routing.clone(), + req.connector.clone(), + ) .await?; - response_handler( - &state, - &merchant_account, - &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), - &payout_data, - ) - .await + response_handler(&merchant_account, &payout_data).await } #[instrument(skip_all)] @@ -472,13 +482,7 @@ pub async fn payouts_retrieve_core( ) .await?; - response_handler( - &state, - &merchant_account, - &payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()), - &payout_data, - ) - .await + response_handler(&merchant_account, &payout_data).await } #[instrument(skip_all)] @@ -563,11 +567,10 @@ pub async fn payouts_cancel_core( .attach_printable("Connector not found for payout cancellation")?, }; - payout_data = cancel_payout( + cancel_payout( &state, &merchant_account, &key_store, - &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), &connector_data, &mut payout_data, ) @@ -575,13 +578,7 @@ pub async fn payouts_cancel_core( .attach_printable("Payout cancellation failed for given Payout request")?; } - response_handler( - &state, - &merchant_account, - &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), - &payout_data, - ) - .await + response_handler(&merchant_account, &payout_data).await } #[instrument(skip_all)] @@ -649,11 +646,10 @@ pub async fn payouts_fulfill_core( .await? .get_required_value("payout_method_data")?, ); - payout_data = fulfill_payout( + fulfill_payout( &state, &merchant_account, &key_store, - &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), &connector_data, &mut payout_data, ) @@ -668,13 +664,7 @@ pub async fn payouts_fulfill_core( })); } - response_handler( - &state, - &merchant_account, - &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), - &payout_data, - ) - .await + response_handler(&merchant_account, &payout_data).await } #[cfg(feature = "olap")] @@ -857,10 +847,9 @@ pub async fn call_connector_payout( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutCreateRequest, connector_data: &api::ConnectorData, - mut payout_data: PayoutData, -) -> RouterResult<PayoutData> { + payout_data: &mut PayoutData, +) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt.to_owned(); let payouts = &payout_data.payouts.to_owned(); @@ -891,13 +880,13 @@ pub async fn call_connector_payout( payout_data.payout_method_data = Some( helpers::make_payout_method_data( state, - req.payout_method_data.as_ref(), + payout_data.payout_method_data.to_owned().as_ref(), payout_attempt.payout_token.as_deref(), &payout_attempt.customer_id, &payout_attempt.merchant_id, Some(&payouts.payout_type), key_store, - Some(&mut payout_data), + Some(payout_data), merchant_account.storage_scheme, ) .await? @@ -905,35 +894,42 @@ pub async fn call_connector_payout( ); } - if let Some(true) = req.confirm { + if let Some(true) = payouts.confirm { // Eligibility flow - payout_data = complete_payout_eligibility( + complete_payout_eligibility( state, merchant_account, key_store, - req, connector_data, payout_data, ) .await?; // Create customer flow - payout_data = complete_create_recipient( + complete_create_recipient( + state, + merchant_account, + key_store, + connector_data, + payout_data, + ) + .await?; + + // Create customer's disbursement account flow + complete_create_recipient_disburse_account( state, merchant_account, key_store, - req, connector_data, payout_data, ) .await?; // Payout creation flow - payout_data = complete_create_payout( + complete_create_payout( state, merchant_account, key_store, - req, connector_data, payout_data, ) @@ -943,57 +939,54 @@ pub async fn call_connector_payout( // Auto fulfillment flow let status = payout_data.payout_attempt.status; if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment { - payout_data = fulfill_payout( + fulfill_payout( state, merchant_account, key_store, - &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), connector_data, - &mut payout_data, + payout_data, ) .await .attach_printable("Payout fulfillment failed for given Payout request")?; } - Ok(payout_data) + Ok(()) } pub async fn complete_create_recipient( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutCreateRequest, connector_data: &api::ConnectorData, - mut payout_data: PayoutData, -) -> RouterResult<PayoutData> { - if payout_data.payout_attempt.status == storage_enums::PayoutStatus::RequiresCreation + payout_data: &mut PayoutData, +) -> RouterResult<()> { + if !payout_data.should_terminate + && payout_data.payout_attempt.status == storage_enums::PayoutStatus::RequiresCreation && connector_data .connector_name .supports_create_recipient(payout_data.payouts.payout_type) { - payout_data = create_recipient( + create_recipient( state, merchant_account, key_store, - req, connector_data, - &mut payout_data, + payout_data, ) .await .attach_printable("Creation of customer failed")?; } - Ok(payout_data) + Ok(()) } pub async fn create_recipient( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutCreateRequest, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, -) -> RouterResult<PayoutData> { +) -> RouterResult<()> { let customer_details = payout_data.customer_details.to_owned(); let connector_name = connector_data.connector_name.to_string(); @@ -1009,12 +1002,11 @@ pub async fn create_recipient( ); if should_call_connector { // 1. Form router data - let customer_router_data = core_utils::construct_payout_router_data( + let router_data = core_utils::construct_payout_router_data( state, - &connector_name, + &connector_data.connector_name, merchant_account, key_store, - &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), payout_data, ) .await?; @@ -1030,8 +1022,8 @@ pub async fn create_recipient( // 3. Call connector service let router_resp = services::execute_connector_processing_step( state, - connector_integration, - &customer_router_data, + connector_integration.to_owned(), + &router_data, payments::CallConnectorAction::Trigger, None, ) @@ -1040,28 +1032,79 @@ pub async fn create_recipient( match router_resp.response { Ok(recipient_create_data) => { + let db = &*state.store; if let Some(customer) = customer_details { - let db = &*state.store; let customer_id = customer.customer_id.to_owned(); let merchant_id = merchant_account.merchant_id.to_owned(); - let updated_customer = storage::CustomerUpdate::ConnectorCustomer { - connector_customer: Some( - serde_json::json!({connector_label: recipient_create_data.connector_payout_id}), - ), + if let Some(updated_customer) = + customers::update_connector_customer_in_customers( + &connector_label, + Some(&customer), + &Some(recipient_create_data.connector_payout_id.clone()), + ) + .await + { + payout_data.customer_details = Some( + db.update_customer_by_customer_id_merchant_id( + customer_id, + merchant_id, + customer, + updated_customer, + key_store, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error updating customers in db")?, + ) + } + } + + // Add next step to ProcessTracker + if recipient_create_data.should_add_next_step_to_process_tracker { + 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)), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while adding attach_payout_account_workflow workflow to process tracker")?; + + // Update payout status in DB + let status = recipient_create_data + .status + .unwrap_or(api_enums::PayoutStatus::RequiresVendorAccountCreation); + let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { + connector_payout_id: recipient_create_data.connector_payout_id, + status, + error_code: None, + error_message: None, + is_eligible: recipient_create_data.payout_eligible, }; - payout_data.customer_details = Some( - db.update_customer_by_customer_id_merchant_id( - customer_id, - merchant_id, - customer, - updated_customer, - key_store, + payout_data.payout_attempt = db + .update_payout_attempt( + &payout_data.payout_attempt, + updated_payout_attempt, + &payout_data.payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error updating customers in db")?, - ) + .attach_printable("Error updating payout_attempt in db")?; + payout_data.payouts = db + .update_payout( + &payout_data.payouts, + storage::PayoutsUpdate::StatusUpdate { status }, + &payout_data.payout_attempt, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error updating payouts in db")?; + + // Helps callee functions skip the execution + payout_data.should_terminate = true; } } Err(err) => Err(errors::ApiErrorResponse::PayoutFailed { @@ -1069,31 +1112,30 @@ pub async fn create_recipient( })?, } } - Ok(payout_data.clone()) + Ok(()) } pub async fn complete_payout_eligibility( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutCreateRequest, connector_data: &api::ConnectorData, - mut payout_data: PayoutData, -) -> RouterResult<PayoutData> { + payout_data: &mut PayoutData, +) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt.to_owned(); - if payout_attempt.is_eligible.is_none() + if !payout_data.should_terminate + && payout_attempt.is_eligible.is_none() && connector_data .connector_name .supports_payout_eligibility(payout_data.payouts.payout_type) { - payout_data = check_payout_eligibility( + check_payout_eligibility( state, merchant_account, key_store, - req, connector_data, - &mut payout_data, + payout_data, ) .await .attach_printable("Eligibility failed for given Payout request")?; @@ -1113,24 +1155,22 @@ pub async fn complete_payout_eligibility( }, )?; - Ok(payout_data) + Ok(()) } pub async fn check_payout_eligibility( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutCreateRequest, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, -) -> RouterResult<PayoutData> { +) -> RouterResult<()> { // 1. Form Router data let router_data = core_utils::construct_payout_router_data( state, - &connector_data.connector_name.to_string(), + &connector_data.connector_name, merchant_account, key_store, - &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), payout_data, ) .await?; @@ -1229,18 +1269,19 @@ pub async fn check_payout_eligibility( } }; - Ok(payout_data.clone()) + Ok(()) } pub async fn complete_create_payout( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutCreateRequest, connector_data: &api::ConnectorData, - mut payout_data: PayoutData, -) -> RouterResult<PayoutData> { - if payout_data.payout_attempt.status == storage_enums::PayoutStatus::RequiresCreation { + payout_data: &mut PayoutData, +) -> RouterResult<()> { + if !payout_data.should_terminate + && payout_data.payout_attempt.status == storage_enums::PayoutStatus::RequiresCreation + { if connector_data .connector_name .supports_instant_payout(payout_data.payouts.payout_type) @@ -1279,36 +1320,33 @@ pub async fn complete_create_payout( .attach_printable("Error updating payouts in db")?; } else { // create payout_object in connector as well as router - payout_data = create_payout( + create_payout( state, merchant_account, key_store, - req, connector_data, - &mut payout_data, + payout_data, ) .await .attach_printable("Payout creation failed for given Payout request")?; } } - Ok(payout_data) + Ok(()) } pub async fn create_payout( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutCreateRequest, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, -) -> RouterResult<PayoutData> { +) -> RouterResult<()> { // 1. Form Router data let mut router_data = core_utils::construct_payout_router_data( state, - &connector_data.connector_name.to_string(), + &connector_data.connector_name, merchant_account, key_store, - &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), payout_data, ) .await?; @@ -1423,24 +1461,135 @@ pub async fn create_payout( } }; - Ok(payout_data.clone()) + Ok(()) +} + +pub async fn complete_create_recipient_disburse_account( + state: &AppState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + connector_data: &api::ConnectorData, + payout_data: &mut PayoutData, +) -> RouterResult<()> { + if !payout_data.should_terminate + && payout_data.payout_attempt.status + == storage_enums::PayoutStatus::RequiresVendorAccountCreation + && connector_data + .connector_name + .supports_vendor_disburse_account_create_for_payout() + { + create_recipient_disburse_account( + state, + merchant_account, + key_store, + connector_data, + payout_data, + ) + .await + .attach_printable("Creation of customer failed")?; + } + Ok(()) +} + +pub async fn create_recipient_disburse_account( + state: &AppState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + connector_data: &api::ConnectorData, + payout_data: &mut PayoutData, +) -> RouterResult<()> { + // 1. Form Router data + let router_data = core_utils::construct_payout_router_data( + state, + &connector_data.connector_name, + merchant_account, + key_store, + payout_data, + ) + .await?; + + // 2. Fetch connector integration details + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::PoRecipientAccount, + types::PayoutsData, + types::PayoutsResponseData, + > = connector_data.connector.get_connector_integration(); + + // 3. Call connector service + let router_data_resp = services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payout_failed_response()?; + + // 4. Process data returned by the connector + let db = &*state.store; + match router_data_resp.response { + Ok(payout_response_data) => { + let payout_attempt = &payout_data.payout_attempt; + let status = payout_response_data + .status + .unwrap_or(payout_attempt.status.to_owned()); + let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { + connector_payout_id: payout_response_data.connector_payout_id, + status, + error_code: None, + error_message: None, + is_eligible: payout_response_data.payout_eligible, + }; + payout_data.payout_attempt = db + .update_payout_attempt( + payout_attempt, + updated_payout_attempt, + &payout_data.payouts, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error updating payout_attempt in db")?; + } + Err(err) => { + let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { + connector_payout_id: String::default(), + status: storage_enums::PayoutStatus::Failed, + error_code: Some(err.code), + error_message: Some(err.message), + is_eligible: None, + }; + payout_data.payout_attempt = db + .update_payout_attempt( + &payout_data.payout_attempt, + updated_payout_attempt, + &payout_data.payouts, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error updating payout_attempt in db")?; + } + }; + + Ok(()) } pub async fn cancel_payout( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutRequest, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, -) -> RouterResult<PayoutData> { +) -> RouterResult<()> { // 1. Form Router data let router_data = core_utils::construct_payout_router_data( state, - &connector_data.connector_name.to_string(), + &connector_data.connector_name, merchant_account, key_store, - req, payout_data, ) .await?; @@ -1531,24 +1680,22 @@ pub async fn cancel_payout( } }; - Ok(payout_data.clone()) + Ok(()) } pub async fn fulfill_payout( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &payouts::PayoutRequest, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, -) -> RouterResult<PayoutData> { +) -> RouterResult<()> { // 1. Form Router data let mut router_data = core_utils::construct_payout_router_data( state, - &connector_data.connector_name.to_string(), + &connector_data.connector_name, merchant_account, key_store, - req, payout_data, ) .await?; @@ -1673,13 +1820,11 @@ pub async fn fulfill_payout( } }; - Ok(payout_data.clone()) + Ok(()) } pub async fn response_handler( - _state: &AppState, merchant_account: &domain::MerchantAccount, - _req: &payouts::PayoutRequest, payout_data: &PayoutData, ) -> RouterResponse<payouts::PayoutCreateResponse> { let payout_attempt = payout_data.payout_attempt.to_owned(); @@ -1837,6 +1982,8 @@ pub async fn payout_create_db_entries( payout_method_id, profile_id: profile_id.to_string(), attempt_count: 1, + metadata: req.metadata.clone(), + confirm: req.confirm, ..Default::default() }; let payouts = db @@ -1900,6 +2047,7 @@ pub async fn payout_create_db_entries( .as_ref() .cloned() .or(stored_payout_method_data.cloned()), + should_terminate: false, profile_id: profile_id.to_owned(), }) } @@ -1974,10 +2122,44 @@ pub async fn make_payout_data( payout_attempt, payout_method_data: None, merchant_connector_account: None, + should_terminate: false, profile_id, }) } +pub async fn add_external_account_addition_task( + db: &dyn StorageInterface, + payout_data: &PayoutData, + schedule_time: time::PrimitiveDateTime, +) -> CustomResult<(), errors::StorageError> { + let runner = storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow; + let task = "STRPE_ATTACH_EXTERNAL_ACCOUNT"; + let tag = ["PAYOUTS", "STRIPE", "ACCOUNT", "CREATE"]; + let process_tracker_id = pt_utils::get_process_tracker_id( + runner, + task, + &payout_data.payout_attempt.payout_attempt_id, + &payout_data.payout_attempt.merchant_id, + ); + let tracking_data = api::PayoutRetrieveRequest { + payout_id: payout_data.payouts.payout_id.to_owned(), + force_sync: None, + merchant_id: Some(payout_data.payouts.merchant_id.to_owned()), + }; + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + tracking_data, + schedule_time, + ) + .map_err(errors::StorageError::from)?; + + db.insert_process(process_tracker_entry).await?; + Ok(()) +} + async fn validate_and_get_business_profile( state: &AppState, profile_id: &String, diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs index af8b016d884..6bbee9a4cec 100644 --- a/crates/router/src/core/payouts/retry.rs +++ b/crates/router/src/core/payouts/retry.rs @@ -1,6 +1,5 @@ use std::{cmp::Ordering, str::FromStr, vec::IntoIter}; -use api_models::payouts::PayoutCreateRequest; use error_stack::{report, ResultExt}; use router_env::{ logger, @@ -32,11 +31,10 @@ pub async fn do_gsm_multiple_connector_actions( state: &app::AppState, mut connectors: IntoIter<api::ConnectorData>, original_connector_data: api::ConnectorData, - mut payout_data: PayoutData, + payout_data: &mut PayoutData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &PayoutCreateRequest, -) -> RouterResult<PayoutData> { +) -> RouterResult<()> { let mut retries = None; metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(&metrics::CONTEXT, 1, &[]); @@ -44,7 +42,7 @@ pub async fn do_gsm_multiple_connector_actions( let mut connector = original_connector_data; loop { - let gsm = get_gsm(state, &connector, &payout_data).await?; + let gsm = get_gsm(state, &connector, payout_data).await?; match get_gsm_decision(gsm) { api_models::gsm::GsmDecision::Retry => { @@ -70,13 +68,12 @@ pub async fn do_gsm_multiple_connector_actions( connector = super::get_next_connector(&mut connectors)?; - payout_data = Box::pin(do_retry( + Box::pin(do_retry( &state.clone(), connector.to_owned(), merchant_account, key_store, payout_data, - req, )) .await?; @@ -92,7 +89,7 @@ pub async fn do_gsm_multiple_connector_actions( api_models::gsm::GsmDecision::DoDefault => break, } } - Ok(payout_data) + Ok(()) } #[instrument(skip_all)] @@ -100,11 +97,10 @@ pub async fn do_gsm_multiple_connector_actions( pub async fn do_gsm_single_connector_actions( state: &app::AppState, original_connector_data: api::ConnectorData, - mut payout_data: PayoutData, + payout_data: &mut PayoutData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - req: &PayoutCreateRequest, -) -> RouterResult<PayoutData> { +) -> RouterResult<()> { let mut retries = None; metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(&metrics::CONTEXT, 1, &[]); @@ -112,7 +108,7 @@ pub async fn do_gsm_single_connector_actions( let mut previous_gsm = None; // to compare previous status loop { - let gsm = get_gsm(state, &original_connector_data, &payout_data).await?; + let gsm = get_gsm(state, &original_connector_data, payout_data).await?; // if the error config is same as previous, we break out of the loop if let Ordering::Equal = gsm.cmp(&previous_gsm) { @@ -136,13 +132,12 @@ pub async fn do_gsm_single_connector_actions( break; } - payout_data = Box::pin(do_retry( + Box::pin(do_retry( &state.clone(), original_connector_data.to_owned(), merchant_account, key_store, payout_data, - req, )) .await?; @@ -158,7 +153,7 @@ pub async fn do_gsm_single_connector_actions( api_models::gsm::GsmDecision::DoDefault => break, } } - Ok(payout_data) + Ok(()) } #[instrument(skip_all)] @@ -245,22 +240,13 @@ pub async fn do_retry( connector: api::ConnectorData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - mut payout_data: PayoutData, - req: &PayoutCreateRequest, -) -> RouterResult<PayoutData> { + payout_data: &mut PayoutData, +) -> RouterResult<()> { metrics::AUTO_RETRY_PAYOUT_COUNT.add(&metrics::CONTEXT, 1, &[]); - modify_trackers(state, &connector, merchant_account, &mut payout_data).await?; + modify_trackers(state, &connector, merchant_account, payout_data).await?; - call_connector_payout( - state, - merchant_account, - key_store, - req, - &connector, - payout_data, - ) - .await + call_connector_payout(state, merchant_account, key_store, &connector, payout_data).await } #[instrument(skip_all)] @@ -363,6 +349,7 @@ impl GsmValidation for PayoutData { | common_enums::PayoutStatus::Ineligible | common_enums::PayoutStatus::RequiresCreation | common_enums::PayoutStatus::RequiresPayoutMethodData + | common_enums::PayoutStatus::RequiresVendorAccountCreation | common_enums::PayoutStatus::RequiresFulfillment => false, common_enums::PayoutStatus::Failed => true, } diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 568e34c04a6..c67aafe938f 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1,11 +1,15 @@ use std::{marker::PhantomData, str::FromStr}; use api_models::enums::{DisputeStage, DisputeStatus}; +#[cfg(feature = "payouts")] +use api_models::payouts::PayoutVendorAccountDetails; use common_enums::{IntentStatus, RequestIncrementalAuthorization}; #[cfg(feature = "payouts")] use common_utils::{crypto::Encryptable, pii::Email}; use common_utils::{errors::CustomResult, ext_traits::AsyncExt}; use error_stack::{report, ResultExt}; +#[cfg(feature = "payouts")] +use masking::PeekInterface; use maud::{html, PreEscaped}; use router_env::{instrument, tracing}; use uuid::Uuid; @@ -31,6 +35,9 @@ use crate::{ pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW: &str = "irrelevant_connector_request_reference_id_in_dispute_flow"; +#[cfg(feature = "payouts")] +pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW: &str = + "irrelevant_connector_request_reference_id_in_payouts_flow"; const IRRELEVANT_PAYMENT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_payment_id_in_dispute_flow"; const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_dispute_flow"; @@ -65,15 +72,14 @@ pub async fn get_mca_for_payout<'a>( #[instrument(skip_all)] pub async fn construct_payout_router_data<'a, F>( state: &'a AppState, - connector_id: &str, + connector_name: &api_models::enums::Connector, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - _request: &api_models::payouts::PayoutRequest, payout_data: &mut PayoutData, ) -> RouterResult<types::PayoutsRouterData<F>> { let merchant_connector_account = get_mca_for_payout( state, - connector_id, + &connector_name.to_string(), merchant_account, key_store, payout_data, @@ -117,25 +123,36 @@ pub async fn construct_payout_router_data<'a, F>( let payouts = &payout_data.payouts; let payout_attempt = &payout_data.payout_attempt; let customer_details = &payout_data.customer_details; - let connector_name = payout_attempt - .connector - .clone() - .get_required_value("connector") - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "Could not decide to route the connector".to_string(), - })?; let connector_label = format!("{}_{}", payout_data.profile_id, connector_name); let connector_customer_id = customer_details .as_ref() .and_then(|c| c.connector_customer.as_ref()) .and_then(|cc| cc.get(connector_label)) .and_then(|id| serde_json::from_value::<String>(id.to_owned()).ok()); + + let vendor_details: Option<PayoutVendorAccountDetails> = + match api_models::enums::PayoutConnectors::try_from(connector_name.to_owned()).map_err( + |err| report!(errors::ApiErrorResponse::InternalServerError).attach_printable(err), + )? { + api_models::enums::PayoutConnectors::Stripe => { + payout_data.payouts.metadata.to_owned().and_then(|meta| { + let val = meta + .peek() + .to_owned() + .parse_value("PayoutVendorAccountDetails") + .ok(); + val + }) + } + _ => None, + }; + let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.merchant_id.to_owned(), customer_id: None, connector_customer: connector_customer_id, - connector: connector_id.to_string(), + connector: connector_name.to_string(), payment_id: "".to_string(), attempt_id: "".to_string(), status: enums::AttemptStatus::Failure, @@ -157,6 +174,7 @@ pub async fn construct_payout_router_data<'a, F>( source_currency: payouts.source_currency, entity_type: payouts.entity_type.to_owned(), payout_type: payouts.payout_type, + vendor_details, customer_details: customer_details .to_owned() .map(|c| payments::CustomerDetails { @@ -174,7 +192,7 @@ pub async fn construct_payout_router_data<'a, F>( payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, - connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW + connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW .to_string(), payout_method_data: payout_data.payout_method_data.to_owned(), quote_id: None, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index feffb7f1e8e..fdabd07fa01 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -71,6 +71,7 @@ pub mod headers { pub const X_WEBHOOK_SIGNATURE: &str = "X-Webhook-Signature-512"; pub const X_REQUEST_ID: &str = "X-Request-Id"; pub const STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE: &str = "Stripe-Signature"; + pub const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; } pub mod pii { diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index f3b6a7cd477..315c6e6bd0a 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -70,7 +70,8 @@ pub async fn payouts_retrieve( ) -> HttpResponse { let payout_retrieve_request = payout_types::PayoutRetrieveRequest { payout_id: path.into_inner(), - force_sync: query_params.force_sync, + force_sync: query_params.force_sync.to_owned(), + merchant_id: query_params.merchant_id.to_owned(), }; let flow = Flow::PayoutsRetrieve; Box::pin(api::server_wrap( diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 6004131be40..a0a085440c8 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -32,7 +32,10 @@ use serde::Serialize; use self::storage::enums as storage_enums; pub use crate::core::payments::{payment_address::PaymentAddress, CustomerDetails}; #[cfg(feature = "payouts")] -use crate::core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW; +use crate::{ + connector::utils::missing_field_err, + core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW, +}; use crate::{ consts, core::{ @@ -190,6 +193,9 @@ pub type PayoutFulfillType = 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>; @@ -308,7 +314,7 @@ pub struct RouterData<Flow, Request, Response> { pub payout_method_data: Option<api::PayoutMethodData>, #[cfg(feature = "payouts")] - /// Contains payout method data + /// Contains payout's quote ID pub quote_id: Option<String>, pub test_mode: Option<bool>, @@ -394,6 +400,23 @@ pub struct PayoutsData { pub payout_type: storage_enums::PayoutType, pub entity_type: storage_enums::PayoutEntityType, pub customer_details: Option<CustomerDetails>, + pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>, +} + +#[cfg(feature = "payouts")] +pub trait PayoutIndividualDetailsExt { + type Error; + fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>; +} + +#[cfg(feature = "payouts")] +impl PayoutIndividualDetailsExt for api_models::payouts::PayoutIndividualDetails { + type Error = error_stack::Report<errors::ConnectorError>; + fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error> { + self.external_account_account_holder_type + .clone() + .ok_or_else(missing_field_err("external_account_account_holder_type")) + } } #[cfg(feature = "payouts")] @@ -402,12 +425,7 @@ pub struct PayoutsResponseData { pub status: Option<storage_enums::PayoutStatus>, pub connector_payout_id: String, pub payout_eligible: Option<bool>, -} - -#[derive(Clone, Debug, Default)] -pub struct PayoutsFulfillResponseData { - pub status: Option<storage_enums::PayoutStatus>, - pub reference_id: Option<String>, + pub should_add_next_step_to_process_tracker: bool, } #[derive(Debug, Clone)] @@ -1587,7 +1605,7 @@ impl<F1, F2> preprocessing_id: None, connector_customer: data.connector_customer.clone(), connector_request_reference_id: - IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW.to_string(), + IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW.to_string(), payout_method_data: data.payout_method_data.clone(), quote_id: data.quote_id.clone(), test_mode: data.test_mode, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 01f4db9ea90..648c7a224eb 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -427,6 +427,7 @@ pub trait Payouts: + PayoutFulfill + PayoutQuote + PayoutRecipient + + PayoutRecipientAccount { } #[cfg(not(feature = "payouts"))] diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs index bed87173b84..a04c2fd095b 100644 --- a/crates/router/src/types/api/payouts.rs +++ b/crates/router/src/types/api/payouts.rs @@ -25,6 +25,9 @@ pub struct PoQuote; #[derive(Debug, Clone)] pub struct PoRecipient; +#[derive(Debug, Clone)] +pub struct PoRecipientAccount; + pub trait PayoutCancel: api::ConnectorIntegration<PoCancel, types::PayoutsData, types::PayoutsResponseData> { @@ -54,3 +57,8 @@ pub trait PayoutRecipient: api::ConnectorIntegration<PoRecipient, types::PayoutsData, types::PayoutsResponseData> { } + +pub trait PayoutRecipientAccount: + api::ConnectorIntegration<PoRecipientAccount, types::PayoutsData, types::PayoutsResponseData> +{ +} diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs index 6158031079c..7b29ded5185 100644 --- a/crates/router/src/workflows.rs +++ b/crates/router/src/workflows.rs @@ -1,5 +1,7 @@ #[cfg(feature = "email")] pub mod api_key_expiry; +#[cfg(feature = "payouts")] +pub mod attach_payout_account_workflow; pub mod outgoing_webhook_retry; pub mod payment_sync; pub mod refund_router; diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rs new file mode 100644 index 00000000000..98d3f7844b4 --- /dev/null +++ b/crates/router/src/workflows/attach_payout_account_workflow.rs @@ -0,0 +1,72 @@ +use common_utils::ext_traits::{OptionExt, ValueExt}; +use scheduler::{ + consumer::{self, workflows::ProcessTrackerWorkflow}, + errors, +}; + +use crate::{ + core::payouts, + errors as core_errors, + routes::AppState, + types::{api, storage}, +}; + +pub struct AttachPayoutAccountWorkflow; + +#[async_trait::async_trait] +impl ProcessTrackerWorkflow<AppState> for AttachPayoutAccountWorkflow { + async fn execute_workflow<'a>( + &'a self, + state: &'a AppState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + // Gather context + let db = &*state.store; + let tracking_data: api::PayoutRetrieveRequest = process + .tracking_data + .clone() + .parse_value("PayoutRetrieveRequest")?; + + let merchant_id = tracking_data + .merchant_id + .clone() + .get_required_value("merchant_id")?; + + let key_store = db + .get_merchant_key_store_by_merchant_id( + 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) + .await?; + + let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data); + + let mut payout_data = + payouts::make_payout_data(state, &merchant_account, &key_store, &request).await?; + + payouts::payouts_core( + state, + &merchant_account, + &key_store, + &mut payout_data, + None, + None, + ) + .await?; + + Ok(()) + } + + async fn error_handler<'a>( + &'a self, + state: &'a AppState, + process: storage::ProcessTracker, + error: errors::ProcessTrackerError, + ) -> core_errors::CustomResult<(), errors::ProcessTrackerError> { + consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await + } +} diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 47ec71cc94e..7f1cd31f305 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -484,6 +484,7 @@ pub trait ConnectorActions: Connector { phone: Some(Secret::new("620874518".to_string())), phone_country_code: Some("+31".to_string()), }), + vendor_details: None, }, payment_info, ) diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index 0f72aa592bf..0b166946758 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -86,6 +86,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { profile_id: new.profile_id.clone(), status: new.status, attempt_count: new.attempt_count, + confirm: new.confirm, }; let redis_entry = kv::TypedSql { @@ -674,6 +675,7 @@ impl DataModelExt for Payouts { profile_id: self.profile_id, status: self.status, attempt_count: self.attempt_count, + confirm: self.confirm, } } @@ -699,6 +701,7 @@ impl DataModelExt for Payouts { profile_id: storage_model.profile_id, status: storage_model.status, attempt_count: storage_model.attempt_count, + confirm: storage_model.confirm, } } } @@ -727,6 +730,7 @@ impl DataModelExt for PayoutsNew { profile_id: self.profile_id, status: self.status, attempt_count: self.attempt_count, + confirm: self.confirm, } } @@ -752,6 +756,7 @@ impl DataModelExt for PayoutsNew { profile_id: storage_model.profile_id, status: storage_model.status, attempt_count: storage_model.attempt_count, + confirm: storage_model.confirm, } } } @@ -771,6 +776,7 @@ impl DataModelExt for PayoutsUpdate { metadata, profile_id, status, + confirm, } => DieselPayoutsUpdate::Update { amount, destination_currency, @@ -783,6 +789,7 @@ impl DataModelExt for PayoutsUpdate { metadata, profile_id, status, + confirm, }, Self::PayoutMethodIdUpdate { payout_method_id } => { DieselPayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } diff --git a/migrations/2024-04-09-202926_add_confirm_to_payouts/down.sql b/migrations/2024-04-09-202926_add_confirm_to_payouts/down.sql new file mode 100644 index 00000000000..ae191c474f0 --- /dev/null +++ b/migrations/2024-04-09-202926_add_confirm_to_payouts/down.sql @@ -0,0 +1 @@ +ALTER TABLE payouts DROP COLUMN IF EXISTS confirm; \ No newline at end of file diff --git a/migrations/2024-04-09-202926_add_confirm_to_payouts/up.sql b/migrations/2024-04-09-202926_add_confirm_to_payouts/up.sql new file mode 100644 index 00000000000..0eccb099525 --- /dev/null +++ b/migrations/2024-04-09-202926_add_confirm_to_payouts/up.sql @@ -0,0 +1 @@ +ALTER TABLE payouts ADD COLUMN IF NOT EXISTS confirm bool; \ No newline at end of file diff --git a/migrations/2024-04-10-034442_alter_payout_status/down.sql b/migrations/2024-04-10-034442_alter_payout_status/down.sql new file mode 100644 index 00000000000..027b7d63fdb --- /dev/null +++ b/migrations/2024-04-10-034442_alter_payout_status/down.sql @@ -0,0 +1 @@ +SELECT 1; \ No newline at end of file diff --git a/migrations/2024-04-10-034442_alter_payout_status/up.sql b/migrations/2024-04-10-034442_alter_payout_status/up.sql new file mode 100644 index 00000000000..80177f5324b --- /dev/null +++ b/migrations/2024-04-10-034442_alter_payout_status/up.sql @@ -0,0 +1 @@ +ALTER TYPE "PayoutStatus" ADD VALUE IF NOT EXISTS 'requires_vendor_account_creation'; \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index b64756fc434..b46a76eb5aa 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -15607,6 +15607,7 @@ "type": "string", "enum": [ "adyen", + "stripe", "wise", "paypal" ] @@ -16211,6 +16212,10 @@ "force_sync": { "type": "boolean", "nullable": true + }, + "merchant_id": { + "type": "string", + "nullable": true } } }, @@ -16233,6 +16238,11 @@ "default": false, "example": true, "nullable": true + }, + "merchant_id": { + "type": "string", + "description": "The identifier for the Merchant Account.", + "nullable": true } } }, @@ -16246,7 +16256,8 @@ "ineligible", "requires_creation", "requires_payout_method_data", - "requires_fulfillment" + "requires_fulfillment", + "requires_vendor_account_creation" ] }, "PayoutType": {
2023-08-29T10:12:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This includes integration of StripeConnect APIs in Stripe connector for payouts functionality. For doing the same, there is an addition of a new Payout connector action (PayoutRecipientAccountCreation). This helps in creation of external accounts (bank / card) for Stripe Connect users. ### 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` --> ## Motivation and Context Stripe Connect is a virtual marketplace for onboarding and paying out to platform's affiliates / vendors / resellers. Integrating Stripe Connect offers payout abstraction for such use-cases. ## How did you test it? - Tested existing payout functionalities using postman test suite. - Tested Stripe Connect integration using raw PMD + SPMs - Postman suite - https://galactic-capsule-229427.postman.co/workspace/My-Workspace~2b563e0d-bad3-420f-8c0b-0fd5b278a4fe/collection/9906252-8f51a4d2-86d6-4f72-8198-3fff5a4e71af?action=share&creator=9906252 ## 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 - [x] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2848e0a3e333ef292130abbeec362f092446270c
juspay/hyperswitch
juspay__hyperswitch-3423
Bug: Audit trail - Add dispute and refund ID to connector calls
diff --git a/crates/analytics/docs/clickhouse/scripts/connector_events.sql b/crates/analytics/docs/clickhouse/scripts/connector_events.sql index 5821cd03556..4a53f9edb0b 100644 --- a/crates/analytics/docs/clickhouse/scripts/connector_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/connector_events.sql @@ -10,7 +10,9 @@ CREATE TABLE connector_events_queue ( `status_code` UInt32, `created_at` DateTime64(3), `latency` UInt128, - `method` LowCardinality(String) + `method` LowCardinality(String), + `refund_id` Nullable(String), + `dispute_id` Nullable(String) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-connector-api-events', kafka_group_name = 'hyper-c1', @@ -32,6 +34,8 @@ CREATE TABLE connector_events_dist ( `inserted_at` DateTime64(3), `latency` UInt128, `method` LowCardinality(String), + `refund_id` Nullable(String), + `dispute_id` Nullable(String), INDEX flowIndex flowTYPE bloom_filter GRANULARITY 1, INDEX connectorIndex connector_name TYPE bloom_filter GRANULARITY 1, INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 @@ -54,7 +58,9 @@ CREATE MATERIALIZED VIEW connector_events_mv TO connector_events_dist ( `status_code` UInt32, `created_at` DateTime64(3), `latency` UInt128, - `method` LowCardinality(String) + `method` LowCardinality(String), + `refund_id` Nullable(String), + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -70,6 +76,8 @@ SELECT now() as inserted_at, latency, method, + refund_id, + dispute_id FROM connector_events_queue where length(_error) = 0; diff --git a/crates/analytics/src/connector_events/events.rs b/crates/analytics/src/connector_events/events.rs index 096520777ee..47044811a8b 100644 --- a/crates/analytics/src/connector_events/events.rs +++ b/crates/analytics/src/connector_events/events.rs @@ -1,7 +1,4 @@ -use api_models::analytics::{ - connector_events::{ConnectorEventsRequest, QueryType}, - Granularity, -}; +use api_models::analytics::{connector_events::ConnectorEventsRequest, Granularity}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -32,11 +29,23 @@ where query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; - match query_param.query_param { - QueryType::Payment { payment_id } => query_builder - .add_filter_clause("payment_id", payment_id) - .switch()?, + + query_builder + .add_filter_clause("payment_id", query_param.payment_id) + .switch()?; + + if let Some(refund_id) = query_param.refund_id { + query_builder + .add_filter_clause("refund_id", &refund_id) + .switch()?; + } + + if let Some(dispute_id) = query_param.dispute_id { + query_builder + .add_filter_clause("dispute_id", &dispute_id) + .switch()?; } + //TODO!: update the execute_query function to return reports instead of plain errors... query_builder .execute_query::<ConnectorEventsResult, _>(pool) diff --git a/crates/api_models/src/analytics/connector_events.rs b/crates/api_models/src/analytics/connector_events.rs index b2974b0a339..7d7e4ae2a8b 100644 --- a/crates/api_models/src/analytics/connector_events.rs +++ b/crates/api_models/src/analytics/connector_events.rs @@ -1,11 +1,6 @@ -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -#[serde(tag = "type")] -pub enum QueryType { - Payment { payment_id: String }, -} - #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ConnectorEventsRequest { - #[serde(flatten)] - pub query_param: QueryType, + pub payment_id: String, + pub refund_id: Option<String>, + pub dispute_id: Option<String>, } diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs index 7f8993af527..8b3eed45f9e 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -119,6 +119,8 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC connector_api_version: None, apple_pay_flow: None, frm_metadata: self.frm_metadata.clone(), + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs index 79b6811a6e9..706a0f9142e 100644 --- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs +++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs @@ -106,6 +106,8 @@ pub async fn construct_fulfillment_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) } diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs index bd0ba3e4f7f..2de6aaab7c7 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -97,6 +97,8 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh connector_api_version: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs index 9c2708b28b3..dfe70570047 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -93,6 +93,8 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp connector_api_version: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs index 5eaa17d3298..a84d9a771b4 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -109,6 +109,8 @@ impl connector_api_version: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs index 25267db1a96..4863edd6fcb 100644 --- a/crates/router/src/core/mandate/utils.rs +++ b/crates/router/src/core/mandate/utils.rs @@ -70,6 +70,8 @@ pub async fn construct_mandate_revoke_router_data( payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 520582eb22f..fe4a7757ecc 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2997,6 +2997,8 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( external_latency: router_data.external_latency, apple_pay_flow: router_data.apple_pay_flow, frm_metadata: router_data.frm_metadata, + refund_id: router_data.refund_id, + dispute_id: router_data.dispute_id, } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 61917fdcd2e..1c1b11c47b1 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -167,6 +167,8 @@ where external_latency: None, apple_pay_flow, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 016d5ec955d..ef8dddde955 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -176,6 +176,8 @@ pub async fn construct_payout_router_data<'a, F>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) @@ -328,6 +330,8 @@ pub async fn construct_refund_router_data<'a, F>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: Some(refund.refund_id.clone()), + dispute_id: None, }; Ok(router_data) @@ -558,6 +562,8 @@ pub async fn construct_accept_dispute_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + dispute_id: Some(dispute.dispute_id.clone()), + refund_id: None, }; Ok(router_data) } @@ -646,6 +652,8 @@ pub async fn construct_submit_evidence_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: Some(dispute.dispute_id.clone()), }; Ok(router_data) } @@ -740,6 +748,8 @@ pub async fn construct_upload_file_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) } @@ -831,6 +841,8 @@ pub async fn construct_defend_dispute_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: Some(dispute.dispute_id.clone()), }; Ok(router_data) } @@ -915,6 +927,8 @@ pub async fn construct_retrieve_file_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) } diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 08b49048043..75d37f94279 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -114,6 +114,8 @@ pub async fn construct_webhook_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) } diff --git a/crates/router/src/events/connector_api_logs.rs b/crates/router/src/events/connector_api_logs.rs index 45c05a3077f..4d3aadc3c45 100644 --- a/crates/router/src/events/connector_api_logs.rs +++ b/crates/router/src/events/connector_api_logs.rs @@ -18,6 +18,8 @@ pub struct ConnectorEvent { created_at: i128, request_id: String, latency: u128, + refund_id: Option<String>, + dispute_id: Option<String>, status_code: u16, } @@ -34,6 +36,8 @@ impl ConnectorEvent { merchant_id: String, request_id: Option<&RequestId>, latency: u128, + refund_id: Option<String>, + dispute_id: Option<String>, status_code: u16, ) -> Self { Self { @@ -54,6 +58,8 @@ impl ConnectorEvent { .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), latency, + refund_id, + dispute_id, status_code, } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index e0c6a086257..cd672405d24 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -400,6 +400,8 @@ where req.merchant_id.clone(), state.request_id.as_ref(), external_latency, + req.refund_id.clone(), + req.dispute_id.clone(), status_code, ); diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 0809ca17820..741a233ae9f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -319,6 +319,9 @@ pub struct RouterData<Flow, Request, Response> { pub apple_pay_flow: Option<storage_enums::ApplePayFlow>, pub frm_metadata: Option<serde_json::Value>, + + pub dispute_id: Option<String>, + pub refund_id: Option<String>, } #[derive(Debug, Clone, serde::Deserialize)] @@ -1466,6 +1469,8 @@ impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)> external_latency: data.external_latency, apple_pay_flow: data.apple_pay_flow.clone(), frm_metadata: data.frm_metadata.clone(), + dispute_id: data.dispute_id.clone(), + refund_id: data.refund_id.clone(), } } } @@ -1522,6 +1527,8 @@ impl<F1, F2> external_latency: data.external_latency, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index fbd94230584..c03f492e8b8 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -103,6 +103,8 @@ impl VerifyConnectorData { external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index c820b7acd6e..d3f8147fb26 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -98,6 +98,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { apple_pay_flow: None, external_latency: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } } @@ -157,6 +159,8 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { apple_pay_flow: None, external_latency: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index ed3cdbe31b5..844777e2dca 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -524,6 +524,8 @@ pub trait ConnectorActions: Connector { apple_pay_flow: None, external_latency: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } }
2024-01-23T08:03:02Z
added refund_id, dispute_id to connector events ## 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 added refund_id, dispute_id for audit trail ## How did you test it? created payment -> created refund for the payment -> checked ConnectorApiLogs for the refund_id ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b2afdc35465426bd11428d8d4ac743617a443128
juspay/hyperswitch
juspay__hyperswitch-3421
Bug: feat: signin and verify email changes for invite flow
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 40d082d1cad..04aabc071ae 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -12,9 +12,9 @@ use crate::user::{ }, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest, - InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignUpRequest, - SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, - UserMerchantCreate, VerifyEmailRequest, + InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignInResponse, + SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, + UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -56,6 +56,7 @@ common_utils::impl_misc_api_event_type!( InviteUserResponse, VerifyEmailRequest, SendVerifyEmailRequest, + SignInResponse, UpdateUserAccountDetailsRequest ); diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 056d1b593dc..89f42f58c39 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -39,7 +39,21 @@ pub struct DashboardEntryResponse { pub type SignInRequest = SignUpRequest; -pub type SignInResponse = DashboardEntryResponse; +#[derive(Debug, serde::Serialize)] +#[serde(tag = "flow_type", rename_all = "snake_case")] +pub enum SignInResponse { + MerchantSelect(MerchantSelectResponse), + DashboardEntry(DashboardEntryResponse), +} + +#[derive(Debug, serde::Serialize)] +pub struct MerchantSelectResponse { + pub token: Secret<String>, + pub name: Secret<String>, + pub email: pii::Email, + pub verification_days_left: Option<i64>, + pub merchants: Vec<UserMerchantAccount>, +} #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct ConnectAccountRequest { @@ -138,7 +152,7 @@ pub struct VerifyEmailRequest { pub token: Secret<String>, } -pub type VerifyEmailResponse = DashboardEntryResponse; +pub type VerifyEmailResponse = SignInResponse; #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct SendVerifyEmailRequest { @@ -149,6 +163,7 @@ pub struct SendVerifyEmailRequest { pub struct UserMerchantAccount { pub merchant_id: String, pub merchant_name: OptionalEncryptableName, + pub is_active: bool, } #[cfg(feature = "recon")] diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 389cb10d7b5..d3b1679378e 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -58,6 +58,8 @@ pub enum UserErrors { InvalidDeleteOperation, #[error("MaxInvitationsError")] MaxInvitationsError, + #[error("RoleNotFound")] + RoleNotFound, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -146,6 +148,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::MaxInvitationsError => { AER::BadRequest(ApiError::new(sub_code, 31, self.get_error_message(), None)) } + Self::RoleNotFound => { + AER::BadRequest(ApiError::new(sub_code, 32, self.get_error_message(), None)) + } } } } @@ -178,6 +183,7 @@ impl UserErrors { Self::ChangePasswordError => "Old and new password cannot be the same", Self::InvalidDeleteOperation => "Delete Operation Not Supported", Self::MaxInvitationsError => "Maximum invite count per request exceeded", + Self::RoleNotFound => "Role Not Found", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c2ed78f8665..ae66728e140 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -97,10 +97,10 @@ pub async fn signup( )) } -pub async fn signin( +pub async fn signin_without_invite_checks( state: AppState, request: user_api::SignInRequest, -) -> UserResponse<user_api::SignInResponse> { +) -> UserResponse<user_api::DashboardEntryResponse> { let user_from_db: domain::UserFromStorage = state .store .find_user_by_email(request.email.clone().expose().expose().as_str()) @@ -124,6 +124,50 @@ pub async fn signin( )) } +pub async fn signin( + state: AppState, + request: user_api::SignInRequest, +) -> UserResponse<user_api::SignInResponse> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_email(request.email.clone().expose().expose().as_str()) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::InvalidCredentials) + } else { + e.change_context(UserErrors::InternalServerError) + } + })? + .into(); + + user_from_db.compare_password(request.password)?; + + let signin_strategy = + if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() { + let preferred_role = user_from_db + .get_role_from_db_by_merchant_id(&state, preferred_merchant_id.as_str()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("User role with preferred_merchant_id not found")?; + domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy { + user: user_from_db, + user_role: preferred_role, + }) + } else { + let user_roles = user_from_db.get_roles_from_db(&state).await?; + domain::SignInWithRoleStrategyType::decide_signin_strategy_by_user_roles( + user_from_db, + user_roles, + ) + .await? + }; + + Ok(ApplicationResponse::Json( + signin_strategy.get_signin_response(&state).await?, + )) +} + #[cfg(feature = "email")] pub async fn connect_account( state: AppState, @@ -832,22 +876,22 @@ pub async fn list_merchant_ids_for_user( state: AppState, user: auth::UserFromToken, ) -> UserResponse<Vec<user_api::UserMerchantAccount>> { - let merchant_ids = utils::user_role::get_merchant_ids_for_user(&state, &user.user_id).await?; + let user_roles = + utils::user_role::get_active_user_roles_for_user(&state, &user.user_id).await?; let merchant_accounts = state .store - .list_multiple_merchant_accounts(merchant_ids) + .list_multiple_merchant_accounts( + user_roles + .iter() + .map(|role| role.merchant_id.clone()) + .collect(), + ) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json( - merchant_accounts - .into_iter() - .map(|acc| user_api::UserMerchantAccount { - merchant_id: acc.merchant_id, - merchant_name: acc.merchant_name, - }) - .collect(), + utils::user::get_multiple_merchant_details_with_status(user_roles, merchant_accounts)?, )) } @@ -868,11 +912,38 @@ pub async fn get_users_for_merchant_account( Ok(ApplicationResponse::Json(user_api::GetUsersResponse(users))) } +#[cfg(feature = "email")] +pub async fn verify_email_without_invite_checks( + state: AppState, + req: user_api::VerifyEmailRequest, +) -> UserResponse<user_api::DashboardEntryResponse> { + let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state) + .await + .change_context(UserErrors::LinkInvalid)?; + let user = state + .store + .find_user_by_email(token.get_email()) + .await + .change_context(UserErrors::InternalServerError)?; + let user = state + .store + .update_user_by_user_id(user.user_id.as_str(), storage_user::UserUpdate::VerifyUser) + .await + .change_context(UserErrors::InternalServerError)?; + let user_from_db: domain::UserFromStorage = user.into(); + let user_role = user_from_db.get_role_from_db(state.clone()).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + + Ok(ApplicationResponse::Json( + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, + )) +} + #[cfg(feature = "email")] pub async fn verify_email( state: AppState, req: user_api::VerifyEmailRequest, -) -> UserResponse<user_api::VerifyEmailResponse> { +) -> UserResponse<user_api::SignInResponse> { let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state) .await .change_context(UserErrors::LinkInvalid)?; @@ -890,11 +961,29 @@ pub async fn verify_email( .change_context(UserErrors::InternalServerError)?; let user_from_db: domain::UserFromStorage = user.into(); - let user_role = user_from_db.get_role_from_db(state.clone()).await?; - let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + + let signin_strategy = + if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() { + let preferred_role = user_from_db + .get_role_from_db_by_merchant_id(&state, preferred_merchant_id.as_str()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("User role with preferred_merchant_id not found")?; + domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy { + user: user_from_db, + user_role: preferred_role, + }) + } else { + let user_roles = user_from_db.get_roles_from_db(&state).await?; + domain::SignInWithRoleStrategyType::decide_signin_strategy_by_user_roles( + user_from_db, + user_roles, + ) + .await? + }; Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, + signin_strategy.get_signin_response(&state).await?, )) } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 44822efddc4..7acb23c40ee 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -952,7 +952,10 @@ impl User { let mut route = web::scope("/user").app_data(web::Data::new(state)); route = route - .service(web::resource("/signin").route(web::post().to(user_signin))) + .service( + web::resource("/signin").route(web::post().to(user_signin_without_invite_checks)), + ) + .service(web::resource("/v2/signin").route(web::post().to(user_signin))) .service(web::resource("/change_password").route(web::post().to(change_password))) .service(web::resource("/internal_signup").route(web::post().to(internal_user_signup))) .service(web::resource("/switch_merchant").route(web::post().to(switch_merchant_id))) @@ -961,14 +964,7 @@ impl User { .route(web::post().to(user_merchant_account_create)), ) .service(web::resource("/switch/list").route(web::get().to(list_merchant_ids_for_user))) - .service(web::resource("/user/list").route(web::get().to(get_user_details))) .service(web::resource("/permission_info").route(web::get().to(get_authorization_info))) - .service(web::resource("/user/update_role").route(web::post().to(update_user_role))) - .service(web::resource("/role/list").route(web::get().to(list_roles))) - .service(web::resource("/role").route(web::get().to(get_role_from_token))) - .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) - .service(web::resource("/user/invite").route(web::post().to(invite_user))) - .service(web::resource("/user/invite/accept").route(web::post().to(accept_invitation))) .service(web::resource("/update").route(web::post().to(update_user_account_details))) .service( web::resource("/user/invite_multiple").route(web::post().to(invite_multiple_user)), @@ -980,6 +976,23 @@ impl User { ) .service(web::resource("/user/delete").route(web::delete().to(delete_user_role))); + // User management + route = route.service( + web::scope("/user") + .service(web::resource("/list").route(web::get().to(get_user_details))) + .service(web::resource("/invite").route(web::post().to(invite_user))) + .service(web::resource("/invite/accept").route(web::post().to(accept_invitation))) + .service(web::resource("/update_role").route(web::post().to(update_user_role))), + ); + + // Role information + route = route.service( + web::scope("/role") + .service(web::resource("").route(web::get().to(get_role_from_token))) + .service(web::resource("/list").route(web::get().to(list_all_roles))) + .service(web::resource("/{role_id}").route(web::get().to(get_role))), + ); + #[cfg(feature = "dummy_connector")] { route = route.service( @@ -1000,7 +1013,11 @@ impl User { web::resource("/signup_with_merchant_id") .route(web::post().to(user_signup_with_merchant_id)), ) - .service(web::resource("/verify_email").route(web::post().to(verify_email))) + .service( + web::resource("/verify_email") + .route(web::post().to(verify_email_without_invite_checks)), + ) + .service(web::resource("/v2/verify_email").route(web::post().to(verify_email))) .service( web::resource("/verify_email_request") .route(web::post().to(verify_email_request)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 6df8c7fb7a7..07894afe732 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -161,6 +161,7 @@ impl From<Flow> for ApiIdentifier { Flow::UserConnectAccount | Flow::UserSignUp + | Flow::UserSignInWithoutInviteChecks | Flow::UserSignIn | Flow::ChangePassword | Flow::SetDashboardMetadata @@ -179,6 +180,7 @@ impl From<Flow> for ApiIdentifier { | Flow::InviteMultipleUser | Flow::DeleteUser | Flow::UserSignUpWithMerchantId + | Flow::VerifyEmailWithoutInviteChecks | Flow::VerifyEmail | Flow::VerifyEmailRequest | Flow::UpdateUserAccountDetails => Self::User, diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 02704cf701f..88e19ddf755 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -58,6 +58,25 @@ pub async fn user_signup( .await } +pub async fn user_signin_without_invite_checks( + state: web::Data<AppState>, + http_req: HttpRequest, + json_payload: web::Json<user_api::SignInRequest>, +) -> HttpResponse { + let flow = Flow::UserSignInWithoutInviteChecks; + let req_payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow.clone(), + state, + &http_req, + req_payload.clone(), + |state, _, req_body| user_core::signin_without_invite_checks(state, req_body), + &auth::NoAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn user_signin( state: web::Data<AppState>, http_req: HttpRequest, @@ -368,6 +387,25 @@ pub async fn invite_multiple_user( .await } +#[cfg(feature = "email")] +pub async fn verify_email_without_invite_checks( + state: web::Data<AppState>, + http_req: HttpRequest, + json_payload: web::Json<user_api::VerifyEmailRequest>, +) -> HttpResponse { + let flow = Flow::VerifyEmailWithoutInviteChecks; + Box::pin(api::server_wrap( + flow.clone(), + state, + &http_req, + json_payload.into_inner(), + |state, _, req_payload| user_core::verify_email_without_invite_checks(state, req_payload), + &auth::NoAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "email")] pub async fn verify_email( state: web::Data<AppState>, diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index f83134e5825..3f9ccda8651 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -29,7 +29,7 @@ pub async fn get_authorization_info( .await } -pub async fn list_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { +pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::ListRoles; Box::pin(api::server_wrap( flow, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index bbe21f289aa..d3ea69ecd86 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -26,11 +26,12 @@ use crate::{ db::StorageInterface, routes::AppState, services::{ + authentication as auth, authentication::UserFromToken, authorization::{info, predefined_permissions}, }, types::transformers::ForeignFrom, - utils::user::password, + utils::{self, user::password}, }; pub mod dashboard_metadata; @@ -733,7 +734,15 @@ impl UserFromStorage { pub async fn get_role_from_db(&self, state: AppState) -> UserResult<UserRole> { state .store - .find_user_role_by_user_id(self.get_user_id()) + .find_user_role_by_user_id(&self.0.user_id) + .await + .change_context(UserErrors::InternalServerError) + } + + pub async fn get_roles_from_db(&self, state: &AppState) -> UserResult<Vec<UserRole>> { + state + .store + .list_user_roles_by_user_id(&self.0.user_id) .await .change_context(UserErrors::InternalServerError) } @@ -760,6 +769,29 @@ impl UserFromStorage { let days_left_for_verification = last_date_for_verification - today; Ok(Some(days_left_for_verification.whole_days())) } + + pub fn get_preferred_merchant_id(&self) -> Option<String> { + self.0.preferred_merchant_id.clone() + } + + pub async fn get_role_from_db_by_merchant_id( + &self, + state: &AppState, + merchant_id: &str, + ) -> UserResult<UserRole> { + state + .store + .find_user_role_by_user_id_merchant_id(self.get_user_id(), merchant_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + UserErrors::RoleNotFound + } else { + UserErrors::InternalServerError + } + }) + .into_report() + } } impl From<info::ModuleInfo> for user_role_api::ModuleInfo { @@ -828,3 +860,101 @@ impl TryFrom<UserAndRoleJoined> for user_api::UserDetails { }) } } + +pub enum SignInWithRoleStrategyType { + SingleRole(SignInWithSingleRoleStrategy), + MultipleRoles(SignInWithMultipleRolesStrategy), +} + +impl SignInWithRoleStrategyType { + pub async fn decide_signin_strategy_by_user_roles( + user: UserFromStorage, + user_roles: Vec<UserRole>, + ) -> UserResult<Self> { + if user_roles.is_empty() { + return Err(UserErrors::InternalServerError.into()); + } + + if let Some(user_role) = user_roles + .iter() + .find(|role| role.status == UserStatus::Active) + { + Ok(Self::SingleRole(SignInWithSingleRoleStrategy { + user, + user_role: user_role.clone(), + })) + } else { + Ok(Self::MultipleRoles(SignInWithMultipleRolesStrategy { + user, + user_roles, + })) + } + } + + pub async fn get_signin_response( + self, + state: &AppState, + ) -> UserResult<user_api::SignInResponse> { + match self { + Self::SingleRole(strategy) => strategy.get_signin_response(state).await, + Self::MultipleRoles(strategy) => strategy.get_signin_response(state).await, + } + } +} + +pub struct SignInWithSingleRoleStrategy { + pub user: UserFromStorage, + pub user_role: UserRole, +} + +impl SignInWithSingleRoleStrategy { + async fn get_signin_response(self, state: &AppState) -> UserResult<user_api::SignInResponse> { + let token = + utils::user::generate_jwt_auth_token(state, &self.user, &self.user_role).await?; + let dashboard_entry_response = + utils::user::get_dashboard_entry_response(state, self.user, self.user_role, token)?; + Ok(user_api::SignInResponse::DashboardEntry( + dashboard_entry_response, + )) + } +} + +pub struct SignInWithMultipleRolesStrategy { + pub user: UserFromStorage, + pub user_roles: Vec<UserRole>, +} + +impl SignInWithMultipleRolesStrategy { + async fn get_signin_response(self, state: &AppState) -> UserResult<user_api::SignInResponse> { + let merchant_accounts = state + .store + .list_multiple_merchant_accounts( + self.user_roles + .iter() + .map(|role| role.merchant_id.clone()) + .collect(), + ) + .await + .change_context(UserErrors::InternalServerError)?; + + let merchant_details = utils::user::get_multiple_merchant_details_with_status( + self.user_roles, + merchant_accounts, + )?; + + Ok(user_api::SignInResponse::MerchantSelect( + user_api::MerchantSelectResponse { + name: self.user.get_name(), + email: self.user.get_email(), + token: auth::UserAuthToken::new_token( + self.user.get_user_id().to_string(), + &state.conf, + ) + .await? + .into(), + merchants: merchant_details, + verification_days_left: utils::user::get_verification_days_left(state, &self.user)?, + }, + )) + } +} diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index a3f9e7978aa..697d10f772e 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -1,5 +1,7 @@ +use std::collections::HashMap; + use api_models::user as user_api; -use diesel_models::user_role::UserRole; +use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use masking::Secret; @@ -118,3 +120,29 @@ pub fn get_verification_days_left( #[cfg(not(feature = "email"))] return Ok(None); } + +pub fn get_multiple_merchant_details_with_status( + user_roles: Vec<UserRole>, + merchant_accounts: Vec<MerchantAccount>, +) -> UserResult<Vec<user_api::UserMerchantAccount>> { + let roles: HashMap<_, _> = user_roles + .into_iter() + .map(|user_role| (user_role.merchant_id.clone(), user_role)) + .collect(); + + merchant_accounts + .into_iter() + .map(|merchant| { + let role = roles + .get(merchant.merchant_id.as_str()) + .ok_or(UserErrors::InternalServerError.into()) + .attach_printable("Merchant exists but user role doesn't")?; + + Ok(user_api::UserMerchantAccount { + merchant_id: merchant.merchant_id.clone(), + merchant_name: merchant.merchant_name.clone(), + is_active: role.status == UserStatus::Active, + }) + }) + .collect() +} diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 65ead92ad34..7ca06aeda0d 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,5 +1,5 @@ use api_models::user_role as user_role_api; -use diesel_models::enums::UserStatus; +use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use crate::{ @@ -17,19 +17,17 @@ pub fn is_internal_role(role_id: &str) -> bool { || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER } -pub async fn get_merchant_ids_for_user(state: &AppState, user_id: &str) -> UserResult<Vec<String>> { +pub async fn get_active_user_roles_for_user( + state: &AppState, + user_id: &str, +) -> UserResult<Vec<UserRole>> { Ok(state .store .list_user_roles_by_user_id(user_id) .await .change_context(UserErrors::InternalServerError)? .into_iter() - .filter_map(|ele| { - if ele.status == UserStatus::Active { - return Some(ele.merchant_id); - } - None - }) + .filter(|ele| ele.status == UserStatus::Active) .collect()) } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 998c52f2c13..0d5710820ee 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -267,6 +267,8 @@ pub enum Flow { UserSignUp, /// User Sign Up UserSignUpWithMerchantId, + /// User Sign In without invite checks + UserSignInWithoutInviteChecks, /// User Sign In UserSignIn, /// User connect account @@ -333,6 +335,8 @@ pub enum Flow { SyncOnboardingStatus, /// Reset tracking id ResetTrackingId, + /// Verify email token without invite checks + VerifyEmailWithoutInviteChecks, /// Verify email Token VerifyEmail, /// Send verify email
2024-01-22T13:11:28Z
## 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 --> This PR adds 2 new APIs 1. `/user/v2/signin` 2. `/user/v2/verify_email` These PRs will have checks as mentioned in the below diagram. ```mermaid flowchart TD A["Connect Account"] -- Email --> B{"User Exists"} B -- No --> C["Create new \n Org \n Merchant \n User \n User Role"] C --> D["Send Verify Email"] D --> E["Verify Email Token"] B -- Yes --> D E --> H{"Is there\n any perferred \nmerchant"} subgraph Checks F -- ==0 --> I{{"Send list of \nmerchants which\n user has access to\n along with an\n intermediate token"}} F -- >=1 --> G[Select the first role with active status] H -- Yes --> M["Send the token \nwith that merchant_id"] H -- No --> F{"How many \n active merchants\n does user have \naccess to"} I -- merchant_ids, \nintermediate_token --> O["Accept Invite"] O --> P["Change status to active"] P --> G G --> M end K["Sign In"] -- Email, Password --> H ``` ### 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` 4. `crates/router/src/configs` 5. `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 make the invitation process for users better. ## 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 curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` or ```curl curl --location 'http://localhost:8080/user/v2/verify_email' \ --header 'Content-Type: application/json' \ --data-raw '{ "token": "email token" }' ``` - Response: - If user has a preferred merchant id or user has a active user role ``` { "flow_type": "dashboard_entry", "token": "JWT with merchant_id, user_id, user_role", "merchant_id": "merchant_id", "name": "user name", "email": "user email", "verification_days_left": null, "user_role": "user role" } ``` - If user has no active user role ``` { "flow_type": "merchant_select", "token": "JWT with only user_id", "merchants": [ { "merchant_id": "merchant_id 1", "company_name": "company_name 1", "is_active": false }, { "merchant_id": "merchant_id 2", "company_name": "company_name 2", "is_active": false } ] } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a59ac7d5b98f27f5fb34206c20ef9c37a07259a3
juspay/hyperswitch
juspay__hyperswitch-3418
Bug: [FEATURE] Add original authorized amount in router data ### Feature Description Add original authorized amount in router data for recurring mandate payments. This field is required in Cybersource for Discover cards recurring mandate payments. ### Possible Implementation Add fields `original_payment_authorized_amount` and `original_payment_authorized_currency` in struct `RecurringMandatePaymentData`. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 72e3de0bf77..db96ff62f6c 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -442,7 +442,7 @@ pub struct ClientRiskInformationRules { #[serde(rename_all = "camelCase")] pub struct Avs { code: String, - code_raw: String, + code_raw: Option<String>, } impl diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 8beb81d9236..7ef47912744 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -10,7 +10,7 @@ use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, - PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RouterData, + PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData, }, consts, core::errors, @@ -47,6 +47,7 @@ impl<T> T, ), ) -> Result<Self, Self::Error> { + // This conversion function is used at different places in the file, if updating this, keep a check for those let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; Ok(Self { amount, @@ -81,11 +82,11 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator { + initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, - }, + }), merchant_intitiated_transaction: None, }), ); @@ -272,14 +273,16 @@ pub enum CybersourceActionsTokenType { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator, + initiator: Option<CybersourcePaymentInitiator>, merchant_intitiated_transaction: Option<MerchantInitiatedTransaction>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantInitiatedTransaction { - reason: String, + reason: Option<String>, + //Required for recurring mandates payment + original_authorized_amount: Option<String>, } #[derive(Debug, Serialize)] @@ -470,35 +473,60 @@ impl From<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>> } impl - From<( + TryFrom<( &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, Option<PaymentSolution>, )> for ProcessingInformation { - fn from( + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( (item, solution): ( &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, Option<PaymentSolution>, ), - ) -> Self { + ) -> Result<Self, Self::Error> { let (action_list, action_token_types, authorization_options) = if item.router_data.request.setup_mandate_details.is_some() { ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator { + initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, - }, + }), merchant_intitiated_transaction: None, }), ) + } else if item.router_data.request.connector_mandate_id().is_some() { + let original_amount = item + .router_data + .get_recurring_mandate_payment_data()? + .get_original_payment_amount()?; + let original_currency = item + .router_data + .get_recurring_mandate_payment_data()? + .get_original_payment_currency()?; + ( + None, + None, + Some(CybersourceAuthorizationOptions { + initiator: None, + merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { + reason: None, + original_authorized_amount: Some(utils::get_amount_as_string( + &types::api::CurrencyUnit::Base, + original_amount, + original_currency, + )?), + }), + }), + ) } else { (None, None, None) }; - Self { + Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None @@ -509,7 +537,7 @@ impl authorization_options, capture_options: None, commerce_indicator: String::from("internet"), - } + }) } } @@ -533,11 +561,11 @@ impl Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator { + initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, - }, + }), merchant_intitiated_transaction: None, }), ) @@ -680,7 +708,7 @@ impl }, }); - let processing_information = ProcessingInformation::from((item, None)); + let processing_information = ProcessingInformation::try_from((item, None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { @@ -792,7 +820,7 @@ impl let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); let processing_information = - ProcessingInformation::from((item, Some(PaymentSolution::ApplePay))); + ProcessingInformation::try_from((item, Some(PaymentSolution::ApplePay)))?; let client_reference_information = ClientReferenceInformation::from(item); let expiration_month = apple_pay_data.get_expiry_month()?; let expiration_year = apple_pay_data.get_four_digit_expiry_year()?; @@ -846,7 +874,7 @@ impl }, }); let processing_information = - ProcessingInformation::from((item, Some(PaymentSolution::GooglePay))); + ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay)))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { @@ -893,10 +921,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> build_bill_to(item.router_data.get_billing()?, email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); - let processing_information = ProcessingInformation::from(( - item, - Some(PaymentSolution::ApplePay), - )); + let processing_information = ProcessingInformation::try_from( + (item, Some(PaymentSolution::ApplePay)), + )?; let client_reference_information = ClientReferenceInformation::from(item); let payment_information = PaymentInformation::ApplePayToken( @@ -1008,7 +1035,7 @@ impl String, ), ) -> Result<Self, Self::Error> { - let processing_information = ProcessingInformation::from((item, None)); + let processing_information = ProcessingInformation::try_from((item, None))?; let payment_instrument = CybersoucrePaymentInstrument { id: connector_mandate_id, }; @@ -1159,13 +1186,14 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout action_list: None, action_token_types: None, authorization_options: Some(CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator { + initiator: Some(CybersourcePaymentInitiator { initiator_type: None, credential_stored_on_file: None, stored_credential_used: Some(true), - }, + }), merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { - reason: "5".to_owned(), + reason: Some("5".to_owned()), + original_authorized_amount: None, }), }), commerce_indicator: String::from("internet"), @@ -1339,18 +1367,6 @@ impl From<CybersourceIncrementalAuthorizationStatus> for common_enums::Authoriza } } -impl From<CybersourcePaymentStatus> for enums::RefundStatus { - fn from(item: CybersourcePaymentStatus) -> Self { - match item { - CybersourcePaymentStatus::Succeeded | CybersourcePaymentStatus::Transmitted => { - Self::Success - } - CybersourcePaymentStatus::Failed => Self::Failure, - _ => Self::Pending, - } - } -} - #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum CybersourcePaymentsResponse { @@ -1430,7 +1446,7 @@ pub struct ClientProcessorInformation { #[serde(rename_all = "camelCase")] pub struct Avs { code: String, - code_raw: String, + code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize)] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 8f028e37a9e..c59fea47612 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -24,7 +24,7 @@ use crate::{ consts, core::{ errors::{self, ApiErrorResponse, CustomResult}, - payments::PaymentData, + payments::{PaymentData, RecurringMandatePaymentData}, }, pii::PeekInterface, types::{ @@ -80,6 +80,7 @@ pub trait RouterData { fn get_customer_id(&self) -> Result<String, Error>; fn get_connector_customer_id(&self) -> Result<String, Error>; fn get_preprocessing_id(&self) -> Result<String, Error>; + fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error>; #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>; #[cfg(feature = "payouts")] @@ -249,6 +250,12 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re .to_owned() .ok_or_else(missing_field_err("preprocessing_id")) } + fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error> { + self.recurring_mandate_payment_data + .to_owned() + .ok_or_else(missing_field_err("recurring_mandate_payment_data")) + } + #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error> { self.payout_method_data @@ -1132,6 +1139,22 @@ impl MandateData for payments::MandateAmountData { } } +pub trait RecurringMandateData { + fn get_original_payment_amount(&self) -> Result<i64, Error>; + fn get_original_payment_currency(&self) -> Result<diesel_models::enums::Currency, Error>; +} + +impl RecurringMandateData for RecurringMandatePaymentData { + fn get_original_payment_amount(&self) -> Result<i64, Error> { + self.original_payment_authorized_amount + .ok_or_else(missing_field_err("original_payment_authorized_amount")) + } + fn get_original_payment_currency(&self) -> Result<diesel_models::enums::Currency, Error> { + self.original_payment_authorized_currency + .ok_or_else(missing_field_err("original_payment_authorized_currency")) + } +} + pub trait MandateReferenceData { fn get_connector_mandate_id(&self) -> Result<String, Error>; } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 043863a98fa..c9e1f6137b7 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2045,6 +2045,8 @@ pub struct IncrementalAuthorizationDetails { #[derive(Debug, Default, Clone)] pub struct RecurringMandatePaymentData { pub payment_method_type: Option<storage_enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe + pub original_payment_authorized_amount: Option<i64>, + pub original_payment_authorized_currency: Option<storage_enums::Currency>, } #[derive(Debug, Default, Clone)] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 213adc79fb0..0cbed255348 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -479,6 +479,27 @@ pub async fn get_token_for_recurring_mandate( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + let original_payment_intent = mandate + .original_payment_id + .as_ref() + .async_map(|payment_id| async { + db.find_payment_intent_by_payment_id_merchant_id( + payment_id, + &mandate.merchant_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .map_err(|err| logger::error!(mandate_original_payment_not_found=?err)) + .ok() + }) + .await + .flatten(); + + let original_payment_authorized_amount = original_payment_intent.clone().map(|pi| pi.amount); + let original_payment_authorized_currency = + original_payment_intent.clone().and_then(|pi| pi.currency); + let customer = req.customer_id.clone().get_required_value("customer_id")?; let payment_method_id = { @@ -540,6 +561,8 @@ pub async fn get_token_for_recurring_mandate( Some(payment_method.payment_method), Some(payments::RecurringMandatePaymentData { payment_method_type, + original_payment_authorized_amount, + original_payment_authorized_currency, }), payment_method.payment_method_type, Some(mandate_connector_details), @@ -550,6 +573,8 @@ pub async fn get_token_for_recurring_mandate( Some(payment_method.payment_method), Some(payments::RecurringMandatePaymentData { payment_method_type, + original_payment_authorized_amount, + original_payment_authorized_currency, }), payment_method.payment_method_type, Some(mandate_connector_details),
2024-01-22T09:35:21Z
## 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 original authorized amount in router data for recurring mandate payments. ### 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/3418 ## 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 can be done by creating a recurring mandate payment in cybersource and using the following discover cards: 6011111111111117, 6011000991300009 Curls: - Payment Intent Create: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 0, "order_details": null, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "cut2", "email": "johndoe@gmail.com", "description": "Hello this is description", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "metadata": {}, "setup_future_usage": "off_session" }' ``` - Payments - Confirm: `curl --location 'http://localhost:8080/payments/{payment_id}/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "off_session": true, "payment_method_data": { "card": { "card_number": "6011000991300009", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 68607706, "currency": "USD" } } } }'` - Payments - Create using Mandates `curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 200, "currency": "USD", "confirm": true, "customer_id": "{customer_id}", "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "capture_method": "automatic", "phone_country_code": "+1", "description": "Its my first payment request", "return_url": "https://google.com", "mandate_id": "{mandate_id}", "off_session":true, "browser_info": { "ip_address":"172.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } } }'` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
629d546aa7c774e86d609abec3b3ab5cf0d100a7
juspay/hyperswitch
juspay__hyperswitch-3407
Bug: Add API doc in README.md for easy access This will help the users to play through the hyperswitch product
diff --git a/README.md b/README.md index dfa77ebe066..0f5e924589f 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,14 @@ The single API to access payment ecosystems across 130+ countries</div> <a href="#%EF%B8%8F-quick-start-guide">Quick Start Guide</a> • <a href="https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md">Local Setup Guide</a> • <a href="#-fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> • + <a href="https://api-reference.hyperswitch.io/introduction"> API Docs </a> • <a href="#-supported-features">Supported Features</a> • - <a href="#-FAQs">FAQs</a> <br> <a href="#whats-included">What's Included</a> • <a href="#-join-us-in-building-hyperswitch">Join us in building HyperSwitch</a> • <a href="#-community">Community</a> • <a href="#-bugs-and-feature-requests">Bugs and feature requests</a> • + <a href="#-FAQs">FAQs</a> • <a href="#-versioning">Versioning</a> • <a href="#%EF%B8%8F-copyright-and-license">Copyright and License</a> </p>
2024-01-19T10:52:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description Add Api Documentation link to the README.md ### 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 Making Api docs accessible to the users. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ec16ed0f82f258c5699d54a386f67aff06c0d144
juspay/hyperswitch
juspay__hyperswitch-3403
Bug: [BUG] [CRYPTOPAY] PSYNC Call Failing ### Bug Description The PSYNC call is failing for connector cryptopay which is resulting in payments getting stuck in the `requires_customer_action` state. ### Expected Behavior The PSYNC should work for connector cryptopay and payments should go into `succeeded`. ### Actual Behavior The PSYNC call is failing for connector cryptopay which is resulting in payments getting stuck in the `requires_customer_action` state. <img width="450" alt="Screenshot 2024-01-19 at 2 55 29 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/ff58a9a5-b062-46f4-be02-1cbcf1d855e0"> <img width="1270" alt="Screenshot 2024-01-19 at 2 55 59 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/46aa4d11-d4f1-453b-bd31-6a61c177c8ba"> ### Steps To Reproduce 1. Create a `crypto_currency` payment for connector `cryptopay`. 2. Try to do PSYNC on the payment. ### Context For The Bug https://juspay.slack.com/archives/C05SDGYKFM1/p1705507357108199 ### Environment ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs index 95ea7ef0c7a..8727461ba34 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/router/src/connector/cryptopay.rs @@ -69,14 +69,24 @@ where req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let api_method = self.get_http_method().to_string(); - let body = types::RequestBody::get_inner_value(self.get_request_body(req, connectors)?) - .peek() - .to_owned(); - let md5_payload = crypto::Md5 - .generate_digest(body.as_bytes()) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - let payload = encode(md5_payload); + let method = self.get_http_method(); + let payload = match method { + common_utils::request::Method::Get => String::default(), + common_utils::request::Method::Post + | common_utils::request::Method::Put + | common_utils::request::Method::Delete + | common_utils::request::Method::Patch => { + let body = + types::RequestBody::get_inner_value(self.get_request_body(req, connectors)?) + .peek() + .to_owned(); + let md5_payload = crypto::Md5 + .generate_digest(body.as_bytes()) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + encode(md5_payload) + } + }; + let api_method = method.to_string(); let now = date_time::date_as_yyyymmddthhmmssmmmz() .into_report()
2024-01-19T09:27:21Z
## 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 --> The encoding for empty string in header generation for PSYNC call is removed. This encoding was previously causing the PSYNC call to fail. ### 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/3403 ## 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 crypto_currency payment for connector cryptopay. `curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 10, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "custo", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "payment_method_data": { "crypto": { "pay_currency": "XRP" } }, "billing": { "address": { "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "test", "quantity": 1, "amount": 10 } ], "business_label": "food", "business_country": "US" }'` - Try to do PSYNC on the payment and status of the payment should be `succeeded` `curl --location 'http://localhost:8080/payments/{payment_id}' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE'` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1c04ac751240f5c931df0f282af1e0ad745e9509
juspay/hyperswitch
juspay__hyperswitch-3395
Bug: Clickhouse - split the ingestion & query tables in separate databases for better access control In order to support our earlier use case where we wanna reduce user confusion etc for tables on grafana, we've decided to restrict grafana (and application) access to query tables only. in order to do this we've decided to separate the query & ingestion database names table format - `hyperswitch_<env>_pub` for query tables & `hyperswitch_<env>` for ingestions tables with this format we will be creating new databases with the `_pub` suffix in this case the Kafka & MV tables would reside in the private db while the cluster & audit tables would reside in the public database... as part of this let's also delete the dist tables and query directly from cluster tables since we don't use sharding... in this case we'll rename the clustered tables to remove the clustered suffix e.g `payment_attempt_clustered -> payment_attempt` The following action items need to be taken - [ ] Create new database with _pub suffix - [ ] Create a replica cluster/audit table in the newer public db & backfill it from the older cluster table - [ ] setup an mv from queue to cluster/audit tables - [x] code changes to change the table name (instead of relying on `payment_attempt_dist` we'll rely on `payment_attempt`) - [x] env changes to specify the newer database names - [ ] update access for the users to have access only to their respective env public databases
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index f81c29c801c..00ae3b6e310 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -354,11 +354,11 @@ impl ToSql<ClickhouseClient> for PrimitiveDateTime { impl ToSql<ClickhouseClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { - Self::Payment => Ok("payment_attempt_dist".to_string()), - Self::Refund => Ok("refund_dist".to_string()), - Self::SdkEvents => Ok("sdk_events_dist".to_string()), - Self::ApiEvents => Ok("api_audit_log".to_string()), - Self::PaymentIntent => Ok("payment_intents_dist".to_string()), + Self::Payment => Ok("payment_attempts".to_string()), + Self::Refund => Ok("refunds".to_string()), + Self::SdkEvents => Ok("sdk_events_audit".to_string()), + Self::ApiEvents => Ok("api_events_audit".to_string()), + Self::PaymentIntent => Ok("payment_intents".to_string()), Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), }
2024-01-18T19:40:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description updated analytics tables of ckh source to new tables ### 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 Segregating tables in ckh for better access control ## 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)? --> - check the analytics tab in dashboard ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cc7e33a5751d97b44c7aba561c974f529ce8824a
juspay/hyperswitch
juspay__hyperswitch-3394
Bug: bug(EVENT_VIEWER): connector events is missing a status code field The status code is being always registered as `0` in clickhouse. ![Image](https://github.com/juspay/hyperswitch/assets/21202349/6c45e608-d976-453d-9594-0312c59abbb9) It seems that we aren't setting the status code at all from the application... we should be able to extract the status code via a simple snippet ```rs let status_code = response .as_ref() .map(|i| i.map_or_else(|value| value.status_code, |value| value.status_code)).unwrap_or_default(); ```
diff --git a/crates/router/src/events/connector_api_logs.rs b/crates/router/src/events/connector_api_logs.rs index 871a7af0d77..45c05a3077f 100644 --- a/crates/router/src/events/connector_api_logs.rs +++ b/crates/router/src/events/connector_api_logs.rs @@ -18,6 +18,7 @@ pub struct ConnectorEvent { created_at: i128, request_id: String, latency: u128, + status_code: u16, } impl ConnectorEvent { @@ -33,6 +34,7 @@ impl ConnectorEvent { merchant_id: String, request_id: Option<&RequestId>, latency: u128, + status_code: u16, ) -> Self { Self { connector_name, @@ -52,6 +54,7 @@ impl ConnectorEvent { .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), latency, + status_code, } } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 307dff55071..7f69954a8f7 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -372,7 +372,13 @@ where let response = call_connector_api(state, request).await; let external_latency = current_time.elapsed().as_millis(); logger::debug!(connector_response=?response); - + let status_code = response + .as_ref() + .map(|i| { + i.as_ref() + .map_or_else(|value| value.status_code, |value| value.status_code) + }) + .unwrap_or_default(); let connector_event = ConnectorEvent::new( req.connector.clone(), std::any::type_name::<T>(), @@ -394,6 +400,7 @@ where req.merchant_id.clone(), state.request_id.as_ref(), external_latency, + status_code, ); match connector_event.try_into() {
2024-01-18T17:37:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description adding status code to connector Kafka events ### 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? f do payment confirm call and then check for the status_code in log in loki where ```topic=hyperswitch-outgoing-connector-events``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0e4e18441d024b7d669b27d6f8a2feb3eccedb2a
juspay/hyperswitch
juspay__hyperswitch-3419
Bug: Logging framework - Add a endrequest log line which should be a common line for accumulating all parameters Currently we use the `EndRequest` filter by actix to rely on this, but we need a log line that represents a request uniquely & contains all the key metadata about the request the list of fields that we need - Flow (already present) - payment_id - connector_name - payment_method
diff --git a/crates/drainer/src/query.rs b/crates/drainer/src/query.rs index f79291f3eae..a1e04fb6d0f 100644 --- a/crates/drainer/src/query.rs +++ b/crates/drainer/src/query.rs @@ -37,7 +37,7 @@ impl ExecuteQuery for kv::DBOperation { ]; let (result, execution_time) = - common_utils::date_time::time_it(|| self.execute(&conn)).await; + Box::pin(common_utils::date_time::time_it(|| self.execute(&conn))).await; push_drainer_delay(pushed_at, operation, table, tags); metrics::QUERY_EXECUTION_TIME.record(&metrics::CONTEXT, execution_time, tags); diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 712ae9e4035..968e6cb07d6 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -245,7 +245,13 @@ pub async fn update_customer_payment_method( .as_ref() .map(|card_network| card_network.to_string()), }; - add_payment_method(state, new_pm, &merchant_account, &key_store).await + Box::pin(add_payment_method( + state, + new_pm, + &merchant_account, + &key_store, + )) + .await } // Wrapper function to switch lockers diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 15d88c94660..f52bce46d8e 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -81,11 +81,11 @@ where ) .await? } else { - save_in_locker( + Box::pin(save_in_locker( state, merchant_account, payment_method_create_request.to_owned(), - ) + )) .await? }; diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index c38a4dc85b5..7b1aba14106 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -267,5 +267,6 @@ pub fn get_application_builder( .wrap(middleware::default_response_headers()) .wrap(middleware::RequestId) .wrap(cors::cors()) + .wrap(middleware::LogSpanInitializer) .wrap(router_env::tracing_actix_web::TracingLogger::default()) } diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index c6c94d3a78e..1feba66a34f 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -1,3 +1,4 @@ +use router_env::tracing::{field::Empty, Instrument}; /// Middleware to include request ID in response header. pub struct RequestId; @@ -48,20 +49,23 @@ where let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>(); let response_fut = self.service.call(req); - Box::pin(async move { - let request_id = request_id_fut.await?; - let request_id = request_id.as_hyphenated().to_string(); - if let Some(upstream_request_id) = old_x_request_id { - router_env::logger::info!(?request_id, ?upstream_request_id); + Box::pin( + async move { + let request_id = request_id_fut.await?; + let request_id = request_id.as_hyphenated().to_string(); + if let Some(upstream_request_id) = old_x_request_id { + router_env::logger::info!(?request_id, ?upstream_request_id); + } + let mut response = response_fut.await?; + response.headers_mut().append( + http::header::HeaderName::from_static("x-request-id"), + http::HeaderValue::from_str(&request_id)?, + ); + + Ok(response) } - let mut response = response_fut.await?; - response.headers_mut().append( - http::header::HeaderName::from_static("x-request-id"), - http::HeaderValue::from_str(&request_id)?, - ); - - Ok(response) - }) + .in_current_span(), + ) } } @@ -81,3 +85,67 @@ pub fn default_response_headers() -> actix_web::middleware::DefaultHeaders { .add((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000")) .add((header::VIA, "HyperSwitch")) } + +/// Middleware to build a TOP level domain span for each request. +pub struct LogSpanInitializer; + +impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for LogSpanInitializer +where + S: actix_web::dev::Service< + actix_web::dev::ServiceRequest, + Response = actix_web::dev::ServiceResponse<B>, + Error = actix_web::Error, + >, + S::Future: 'static, + B: 'static, +{ + type Response = actix_web::dev::ServiceResponse<B>; + type Error = actix_web::Error; + type Transform = LogSpanInitializerMiddleware<S>; + type InitError = (); + type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; + + fn new_transform(&self, service: S) -> Self::Future { + std::future::ready(Ok(LogSpanInitializerMiddleware { service })) + } +} + +pub struct LogSpanInitializerMiddleware<S> { + service: S, +} + +impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> + for LogSpanInitializerMiddleware<S> +where + S: actix_web::dev::Service< + actix_web::dev::ServiceRequest, + Response = actix_web::dev::ServiceResponse<B>, + Error = actix_web::Error, + >, + S::Future: 'static, + B: 'static, +{ + type Response = actix_web::dev::ServiceResponse<B>; + type Error = actix_web::Error; + type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; + + actix_web::dev::forward_ready!(service); + + // TODO: have a common source of truth for the list of top level fields + // /crates/router_env/src/logger/storage.rs also has a list of fields called PERSISTENT_KEYS + fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { + let response_fut = self.service.call(req); + + Box::pin( + response_fut.instrument( + router_env::tracing::info_span!( + "golden_log_line", + payment_id = Empty, + merchant_id = Empty, + connector_name = Empty + ) + .or_current(), + ), + ) + } +} diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index ab404125a38..f5a6a49b9c9 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -520,7 +520,7 @@ pub async fn business_profile_update( let flow = Flow::BusinessProfileUpdate; let (merchant_id, profile_id) = path.into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -535,7 +535,7 @@ pub async fn business_profile_update( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } #[instrument(skip_all, fields(flow = ?Flow::BusinessProfileDelete))] diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 468d202b94c..342fe23c38a 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -75,7 +75,7 @@ pub async fn revoke_mandate( let mandate_id = mandates::MandateId { mandate_id: path.into_inner(), }; - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -85,7 +85,7 @@ pub async fn revoke_mandate( }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, - ) + )) .await } /// Mandates - List Mandates diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 6ef5de886be..55564a6386f 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -44,7 +44,13 @@ pub async fn create_payment_method_api( &req, json_payload.into_inner(), |state, auth, req| async move { - cards::add_payment_method(state, req, &auth.merchant_account, &auth.key_store).await + Box::pin(cards::add_payment_method( + state, + req, + &auth.merchant_account, + &auth.key_store, + )) + .await }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index ad463fcf2b9..307dff55071 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1131,7 +1131,6 @@ where status_code = response_code, time_taken_ms = request_duration.as_millis(), ); - res } diff --git a/crates/router_env/src/logger/storage.rs b/crates/router_env/src/logger/storage.rs index 51e701213b9..961a77c65aa 100644 --- a/crates/router_env/src/logger/storage.rs +++ b/crates/router_env/src/logger/storage.rs @@ -92,6 +92,8 @@ impl Visit for Storage<'_> { } } +const PERSISTENT_KEYS: [&str; 3] = ["payment_id", "connector_name", "merchant_id"]; + impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S> for StorageSubscription { @@ -99,6 +101,7 @@ impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(id).expect("No span"); + let mut extensions = span.extensions_mut(); let mut visitor = if let Some(parent_span) = span.parent() { let mut extensions = parent_span.extensions_mut(); @@ -110,7 +113,6 @@ impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer Storage::default() }; - let mut extensions = span.extensions_mut(); attrs.record(&mut visitor); extensions.insert(visitor); } @@ -150,6 +152,18 @@ impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer .unwrap_or(0) }; + if let Some(s) = span.extensions().get::<Storage<'_>>() { + s.values.iter().for_each(|(k, v)| { + if PERSISTENT_KEYS.contains(k) { + span.parent().and_then(|p| { + p.extensions_mut() + .get_mut::<Storage<'_>>() + .map(|s| s.values.insert(k, v.to_owned())) + }); + } + }) + }; + let mut extensions_mut = span.extensions_mut(); #[allow(clippy::expect_used)] let visitor = extensions_mut diff --git a/docker-compose-development.yml b/docker-compose-development.yml index 5a3eca4cdf3..665bdf2f05d 100644 --- a/docker-compose-development.yml +++ b/docker-compose-development.yml @@ -31,7 +31,7 @@ services: networks: - router_net ports: - - "6379" + - "6379:6379" migration_runner: image: rust:latest diff --git a/docker-compose.yml b/docker-compose.yml index 9f8e7bb4efb..3839269a522 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -27,7 +27,7 @@ services: networks: - router_net ports: - - "6379" + - "6379:6379" migration_runner: image: rust:latest
2024-01-24T06:55:33Z
## 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 --> - Create a request middleware to create a top level span consisting of all the metadata fields - Update the subscriber layer to propogate the metadata fields to the top layer ### 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 don't have guaranteed keys/metadata present at the top level - finding the relavant info (payment_id/connector etc) requires context about the lower level functions where this info is extracted - instead this change provides a single log line that is guaranteed to be present for all API calls - And this log line would have all the relevant fields needed for analysis/debugging ## 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 the application locally all api requests should have the following log line at the end of request - the fields should be populated when available - These log line will be generated even for health & non-existent paths (e.g `/` or `/favicon.ico`) ```json { "message": "[GOLDEN_LOG_LINE - EVENT] REQUEST MIDDLEWARE END", "hostname": "<MY_MACHINE>.local", "pid": 62901, "env": "development", "level": "INFO", "target": "router::middleware", "service": "router", "line": 61, "file": "crates/router/src/middleware.rs", "fn": "golden_log_line", "full_name": "router::middleware::golden_log_line", "time": "2024-01-24T06:35:06.771569000Z", "merchant_id": "merchant_1706060159", "request_id": "018d3a2d-e583-7581-8992-8596b3052995", "extra": { "trace_id": "00000000000000000000000000000000", "http.method": "POST", "http.route": "/payments", "http.flavor": "1.1", "http.user_agent": "PostmanRuntime/7.33.0", "payment_id": "payment_intent_id = \"pay_y8XHx5whOaWTdoGrgAAf\"", "otel.name": "HTTP POST /payments", "http.client_ip": "::1", "http.host": "localhost:8080", "http.target": "/payments", "http.scheme": "http", "otel.kind": "server" } } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cc7e33a5751d97b44c7aba561c974f529ce8824a
juspay/hyperswitch
juspay__hyperswitch-3390
Bug: feat: delete / deactivate user Add endpoint to support a delete user. A user who is part of the organisation can be deleted by users with permission `UsersWrite`, provided user to be deleted should not be the org admin or internal user.
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index c8d8fd96a7a..3ec30d6bd97 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -1,8 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ - AcceptInvitationRequest, AuthorizationInfoResponse, GetRoleRequest, ListRolesResponse, - RoleInfoResponse, UpdateUserRoleRequest, + AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, GetRoleRequest, + ListRolesResponse, RoleInfoResponse, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( @@ -11,5 +11,6 @@ common_utils::impl_misc_api_event_type!( GetRoleRequest, AuthorizationInfoResponse, UpdateUserRoleRequest, - AcceptInvitationRequest + AcceptInvitationRequest, + DeleteUserRoleRequest ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index d2548935f62..e8c9b777c7f 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,3 +1,5 @@ +use common_utils::pii; + use crate::user::DashboardEntryResponse; #[derive(Debug, serde::Serialize)] @@ -101,3 +103,8 @@ pub struct AcceptInvitationRequest { } pub type AcceptInvitationResponse = DashboardEntryResponse; + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct DeleteUserRoleRequest { + pub email: pii::Email, +} diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rs index 678bcc2fd1f..b1cb034eb1f 100644 --- a/crates/diesel_models/src/query/dashboard_metadata.rs +++ b/crates/diesel_models/src/query/dashboard_metadata.rs @@ -104,4 +104,18 @@ impl DashboardMetadata { ) .await } + + pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + ) -> StorageResult<bool> { + generics::generic_delete::<<Self as HasTable>::Table, _>( + conn, + dsl::user_id + .eq(user_id) + .and(dsl::merchant_id.eq(merchant_id)), + ) + .await + } } diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index 6b408038ef5..e67eba64c7c 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -54,9 +54,18 @@ impl UserRole { .await } - pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: String) -> StorageResult<bool> { - generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::user_id.eq(user_id)) - .await + pub async fn delete_by_user_id_merchant_id( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + ) -> StorageResult<bool> { + generics::generic_delete::<<Self as HasTable>::Table, _>( + conn, + dsl::user_id + .eq(user_id) + .and(dsl::merchant_id.eq(merchant_id)), + ) + .await } pub async fn list_by_user_id(conn: &PgPooledConn, user_id: String) -> StorageResult<Vec<Self>> { diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 330e02cd547..f4000755b3e 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -54,6 +54,8 @@ pub enum UserErrors { MerchantIdParsingError, #[error("ChangePasswordError")] ChangePasswordError, + #[error("InvalidDeleteOperation")] + InvalidDeleteOperation, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -157,6 +159,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon "Old and new password cannot be same", None, )), + Self::InvalidDeleteOperation => AER::BadRequest(ApiError::new( + sub_code, + 30, + "Delete Operation Not Supported", + None, + )), } } } diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 245f8d246d2..742c281b89a 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,6 +1,7 @@ use api_models::user_role as user_role_api; use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate}; use error_stack::ResultExt; +use masking::ExposeInterface; use router_env::logger; use crate::{ @@ -11,6 +12,7 @@ use crate::{ authorization::{info, predefined_permissions}, ApplicationResponse, }, + types::domain, utils, }; @@ -161,3 +163,88 @@ pub async fn accept_invitation( Ok(ApplicationResponse::StatusOk) } + +pub async fn delete_user_role( + state: AppState, + user_from_token: auth::UserFromToken, + request: user_role_api::DeleteUserRoleRequest, +) -> UserResponse<()> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_email( + domain::UserEmail::from_pii_email(request.email)? + .get_secret() + .expose() + .as_str(), + ) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::InvalidRoleOperation) + .attach_printable("User not found in records") + } else { + e.change_context(UserErrors::InternalServerError) + } + })? + .into(); + + if user_from_db.get_user_id() == user_from_token.user_id { + return Err(UserErrors::InvalidDeleteOperation.into()) + .attach_printable("User deleting himself"); + } + + let user_roles = state + .store + .list_user_roles_by_user_id(user_from_db.get_user_id()) + .await + .change_context(UserErrors::InternalServerError)?; + + match user_roles + .iter() + .find(|&role| role.merchant_id == user_from_token.merchant_id.as_str()) + { + Some(user_role) => { + if !predefined_permissions::is_role_deletable(&user_role.role_id) { + return Err(UserErrors::InvalidRoleId.into()) + .attach_printable("Deletion not allowed for users with specific role id"); + } + } + None => { + return Err(UserErrors::InvalidDeleteOperation.into()) + .attach_printable("User is not associated with the merchant"); + } + }; + + if user_roles.len() > 1 { + state + .store + .delete_user_role_by_user_id_merchant_id( + user_from_db.get_user_id(), + user_from_token.merchant_id.as_str(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user role")?; + + Ok(ApplicationResponse::StatusOk) + } else { + state + .store + .delete_user_by_user_id(user_from_db.get_user_id()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user entry")?; + + state + .store + .delete_user_role_by_user_id_merchant_id( + user_from_db.get_user_id(), + user_from_token.merchant_id.as_str(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user role")?; + + Ok(ApplicationResponse::StatusOk) + } +} diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs index ec24b4ed07d..8e2ac0b6ad3 100644 --- a/crates/router/src/db/dashboard_metadata.rs +++ b/crates/router/src/db/dashboard_metadata.rs @@ -36,6 +36,12 @@ pub trait DashboardMetadataInterface { org_id: &str, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] @@ -111,6 +117,21 @@ impl DashboardMetadataInterface for Store { .map_err(Into::into) .into_report() } + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() + } } #[async_trait::async_trait] @@ -246,4 +267,31 @@ impl DashboardMetadataInterface for MockDb { } Ok(query_result) } + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let mut dashboard_metadata = self.dashboard_metadata.lock().await; + + let initial_len = dashboard_metadata.len(); + + dashboard_metadata.retain(|metadata_inner| { + !(metadata_inner + .user_id + .clone() + .map(|user_id_inner| user_id_inner == user_id) + .unwrap_or(false) + && metadata_inner.merchant_id == merchant_id) + }); + + if dashboard_metadata.len() == initial_len { + return Err(errors::StorageError::ValueNotFound(format!( + "No user available for user_id = {user_id} and merchant id = {merchant_id}" + )) + .into()); + } + + Ok(true) + } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8398c153156..e88d59ea9f3 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1955,9 +1955,14 @@ impl UserRoleInterface for KafkaStore { .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update) .await } - - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { - self.diesel_store.delete_user_role(user_id).await + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_role_by_user_id_merchant_id(user_id, merchant_id) + .await } async fn list_user_roles_by_user_id( @@ -2017,6 +2022,16 @@ impl DashboardMetadataInterface for KafkaStore { .find_merchant_scoped_dashboard_metadata(merchant_id, org_id, data_keys) .await } + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index d8938f9683d..f02e6d60b3b 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -32,8 +32,11 @@ pub trait UserRoleInterface { merchant_id: &str, update: storage::UserRoleUpdate, ) -> CustomResult<storage::UserRole, errors::StorageError>; - - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError>; + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError>; async fn list_user_roles_by_user_id( &self, @@ -100,12 +103,20 @@ impl UserRoleInterface for Store { .into_report() } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::delete_by_user_id(&conn, user_id.to_owned()) - .await - .map_err(Into::into) - .into_report() + storage::UserRole::delete_by_user_id_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() } async fn list_user_roles_by_user_id( @@ -230,11 +241,17 @@ impl UserRoleInterface for MockDb { ) } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; let user_role_index = user_roles .iter() - .position(|user_role| user_role.user_id == user_id) + .position(|user_role| { + user_role.user_id == user_id && user_role.merchant_id == merchant_id + }) .ok_or(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )))?; @@ -286,8 +303,14 @@ impl UserRoleInterface for super::KafkaStore { ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store.find_user_role_by_user_id(user_id).await } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { - self.diesel_store.delete_user_role(user_id).await + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_role_by_user_id_merchant_id(user_id, merchant_id) + .await } async fn list_user_roles_by_user_id( &self, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 4345109a672..5922eeb9fee 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -928,7 +928,8 @@ impl User { web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) .route(web::post().to(set_dashboard_metadata)), - ); + ) + .service(web::resource("/user/delete").route(web::delete().to(delete_user_role))); #[cfg(feature = "dummy_connector")] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1c967222dc7..30348513c2b 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -176,6 +176,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ForgotPassword | Flow::ResetPassword | Flow::InviteUser + | Flow::DeleteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmail | Flow::VerifyEmailRequest diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 73b1ef1b01d..f83134e5825 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -115,3 +115,21 @@ pub async fn accept_invitation( )) .await } + +pub async fn delete_user_role( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<user_role_api::DeleteUserRoleRequest>, +) -> HttpResponse { + let flow = Flow::DeleteUser; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload.into_inner(), + user_role_core::delete_user_role, + &auth::JWTAuth(Permission::UsersWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs index c489f1fc963..6fe0ddcc360 100644 --- a/crates/router/src/services/authorization/predefined_permissions.rs +++ b/crates/router/src/services/authorization/predefined_permissions.rs @@ -9,6 +9,7 @@ pub struct RoleInfo { permissions: Vec<Permission>, name: Option<&'static str>, is_invitable: bool, + is_deletable: bool, } impl RoleInfo { @@ -63,6 +64,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: None, is_invitable: false, + is_deletable: false, }, ); roles.insert( @@ -87,6 +89,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: None, is_invitable: false, + is_deletable: false, }, ); @@ -126,6 +129,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Organization Admin"), is_invitable: false, + is_deletable: false, }, ); @@ -165,6 +169,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Admin"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -189,6 +194,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("View Only"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -214,6 +220,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("IAM"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -239,6 +246,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Developer"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -269,6 +277,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Operator"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -291,6 +300,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Customer Support"), is_invitable: true, + is_deletable: true, }, ); roles @@ -307,3 +317,9 @@ pub fn is_role_invitable(role_id: &str) -> bool { .get(role_id) .map_or(false, |role_info| role_info.is_invitable) } + +pub fn is_role_deletable(role_id: &str) -> bool { + PREDEFINED_PERMISSIONS + .get(role_id) + .map_or(false, |role_info| role_info.is_deletable) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ba323ebc5e3..84f2e3e1267 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -321,6 +321,8 @@ pub enum Flow { ResetPassword, /// Invite users InviteUser, + /// Delete user + DeleteUser, /// Incremental Authorization flow PaymentsIncrementalAuthorization, /// Get action URL for connector onboarding
2024-01-17T13:43:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add add new endpoint `/user/user/delete` that deletes the user present in the merchant account Here we have two scenarios - When user is related to more than one merchant accounts: Delete the user role for that particular merchant account. User will be present in other accounts. - When user is part of one merchant account: Delete user role and user completely. ### 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 Currently there is no endpoint to remove the invited users ## How did you test it? - Singup/Singin Use the following curl to invite users: ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user2@juspay.in", "name": "user2", "role_id": "merchant_admin" } ``` Use the following curl to delete invited user: ``` curl --location 'http://localhost:8080/user/user/delete' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "invite_from_test21521@juspay.in" }' ``` Cases to handle: - only users with permission UsersWrite can delete - org_admin cannot be deleted - internal users cannot be deleted - user cannot delete himself ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cc7e33a5751d97b44c7aba561c974f529ce8824a
juspay/hyperswitch
juspay__hyperswitch-3386
Bug: feat: get user role from token
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 72fca2b2f08..b057f8ca8bc 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -43,6 +43,7 @@ pub enum Permission { SurchargeDecisionManagerRead, UsersRead, UsersWrite, + MerchantAccountCreate, } #[derive(Debug, serde::Serialize)] @@ -60,6 +61,7 @@ pub enum PermissionModule { Files, ThreeDsDecisionManager, SurchargeDecisionManager, + AccountCreate, } #[derive(Debug, serde::Serialize)] diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 2b7752d1904..d8ff836e1f8 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -20,7 +20,7 @@ pub async fn get_authorization_info( user_role_api::AuthorizationInfoResponse( info::get_authorization_info() .into_iter() - .filter_map(|module| module.try_into().ok()) + .map(Into::into) .collect(), ), )) @@ -63,6 +63,22 @@ pub async fn get_role( Ok(ApplicationResponse::Json(info)) } +pub async fn get_role_from_token( + _state: AppState, + user: auth::UserFromToken, +) -> UserResponse<Vec<user_role_api::Permission>> { + Ok(ApplicationResponse::Json( + predefined_permissions::PREDEFINED_PERMISSIONS + .get(user.role_id.as_str()) + .ok_or(UserErrors::InternalServerError.into()) + .attach_printable("Invalid Role Id in JWT")? + .get_permissions() + .iter() + .map(|&per| per.into()) + .collect(), + )) +} + pub async fn update_user_role( state: AppState, user_from_token: auth::UserFromToken, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0c489dbe63a..34a3b5db51b 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -919,6 +919,7 @@ impl User { .service(web::resource("/permission_info").route(web::get().to(get_authorization_info))) .service(web::resource("/user/update_role").route(web::post().to(update_user_role))) .service(web::resource("/role/list").route(web::get().to(list_roles))) + .service(web::resource("/role").route(web::get().to(get_role_from_token))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service( diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 12cf76be475..4dffcb1d38d 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -180,9 +180,11 @@ impl From<Flow> for ApiIdentifier { | Flow::VerifyEmail | Flow::VerifyEmailRequest => Self::User, - Flow::ListRoles | Flow::GetRole | Flow::UpdateUserRole | Flow::GetAuthorizationInfo => { - Self::UserRole - } + Flow::ListRoles + | Flow::GetRole + | Flow::GetRoleFromToken + | Flow::UpdateUserRole + | Flow::GetAuthorizationInfo => Self::UserRole, Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index c96e099ab16..fe305942d03 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -7,7 +7,7 @@ use crate::{ core::{api_locking, user_role as user_role_core}, services::{ api, - authentication::{self as auth}, + authentication::{self as auth, UserFromToken}, authorization::permissions::Permission, }, }; @@ -64,6 +64,20 @@ pub async fn get_role( .await } +pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::GetRoleFromToken; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user: UserFromToken, _| user_role_core::get_role_from_token(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn update_user_role( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index cef93f82739..99e4f1b6c09 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -15,16 +15,13 @@ pub struct PermissionInfo { impl PermissionInfo { pub fn new(permissions: &[Permission]) -> Vec<Self> { - let mut permission_infos = Vec::with_capacity(permissions.len()); - for permission in permissions { - if let Some(description) = Permission::get_permission_description(permission) { - permission_infos.push(Self { - enum_name: permission.clone(), - description, - }) - } - } - permission_infos + permissions + .iter() + .map(|&per| Self { + description: Permission::get_permission_description(&per), + enum_name: per, + }) + .collect() } } @@ -43,6 +40,7 @@ pub enum PermissionModule { Files, ThreeDsDecisionManager, SurchargeDecisionManager, + AccountCreate, } impl PermissionModule { @@ -60,7 +58,8 @@ impl PermissionModule { Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module", Self::Files => "Permissions for uploading, deleting and viewing files for disputes", Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant", - Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant" + Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant", + Self::AccountCreate => "Create new account within your organization" } } } @@ -173,6 +172,11 @@ impl ModuleInfo { Permission::SurchargeDecisionManagerRead, ]), }, + PermissionModule::AccountCreate => Self { + module: module_name, + description, + permissions: PermissionInfo::new(&[Permission::MerchantAccountCreate]), + }, } } } diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 426b048e88b..5c5e3ecce30 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -1,6 +1,6 @@ use strum::Display; -#[derive(PartialEq, Display, Clone, Debug)] +#[derive(PartialEq, Display, Clone, Debug, Copy)] pub enum Permission { PaymentRead, PaymentWrite, @@ -34,45 +34,43 @@ pub enum Permission { } impl Permission { - pub fn get_permission_description(&self) -> Option<&'static str> { + pub fn get_permission_description(&self) -> &'static str { match self { - Self::PaymentRead => Some("View all payments"), - Self::PaymentWrite => Some("Create payment, download payments data"), - Self::RefundRead => Some("View all refunds"), - Self::RefundWrite => Some("Create refund, download refunds data"), - Self::ApiKeyRead => Some("View API keys (masked generated for the system"), - Self::ApiKeyWrite => Some("Create and update API keys"), - Self::MerchantAccountRead => Some("View merchant account details"), + Self::PaymentRead => "View all payments", + Self::PaymentWrite => "Create payment, download payments data", + Self::RefundRead => "View all refunds", + Self::RefundWrite => "Create refund, download refunds data", + Self::ApiKeyRead => "View API keys (masked generated for the system", + Self::ApiKeyWrite => "Create and update API keys", + Self::MerchantAccountRead => "View merchant account details", Self::MerchantAccountWrite => { - Some("Update merchant account details, configure webhooks, manage api keys") + "Update merchant account details, configure webhooks, manage api keys" } - Self::MerchantConnectorAccountRead => Some("View connectors configured"), + Self::MerchantConnectorAccountRead => "View connectors configured", Self::MerchantConnectorAccountWrite => { - Some("Create, update, verify and delete connector configurations") + "Create, update, verify and delete connector configurations" } - Self::ForexRead => Some("Query Forex data"), - Self::RoutingRead => Some("View routing configuration"), - Self::RoutingWrite => Some("Create and activate routing configurations"), - Self::DisputeRead => Some("View disputes"), - Self::DisputeWrite => Some("Create and update disputes"), - Self::MandateRead => Some("View mandates"), - Self::MandateWrite => Some("Create and update mandates"), - Self::CustomerRead => Some("View customers"), - Self::CustomerWrite => Some("Create, update and delete customers"), - Self::FileRead => Some("View files"), - Self::FileWrite => Some("Create, update and delete files"), - Self::Analytics => Some("Access to analytics module"), - Self::ThreeDsDecisionManagerWrite => Some("Create and update 3DS decision rules"), + Self::ForexRead => "Query Forex data", + Self::RoutingRead => "View routing configuration", + Self::RoutingWrite => "Create and activate routing configurations", + Self::DisputeRead => "View disputes", + Self::DisputeWrite => "Create and update disputes", + Self::MandateRead => "View mandates", + Self::MandateWrite => "Create and update mandates", + Self::CustomerRead => "View customers", + Self::CustomerWrite => "Create, update and delete customers", + Self::FileRead => "View files", + Self::FileWrite => "Create, update and delete files", + Self::Analytics => "Access to analytics module", + Self::ThreeDsDecisionManagerWrite => "Create and update 3DS decision rules", Self::ThreeDsDecisionManagerRead => { - Some("View all 3DS decision rules configured for a merchant") + "View all 3DS decision rules configured for a merchant" } - Self::SurchargeDecisionManagerWrite => { - Some("Create and update the surcharge decision rules") - } - Self::SurchargeDecisionManagerRead => Some("View all the surcharge decision rules"), - Self::UsersRead => Some("View all the users for a merchant"), - Self::UsersWrite => Some("Invite users, assign and update roles"), - Self::MerchantAccountCreate => None, + Self::SurchargeDecisionManagerWrite => "Create and update the surcharge decision rules", + Self::SurchargeDecisionManagerRead => "View all the surcharge decision rules", + Self::UsersRead => "View all the users for a merchant", + Self::UsersWrite => "Invite users, assign and update roles", + Self::MerchantAccountCreate => "Create merchant account", } } } diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index d271ed5e29d..53c88f8aea1 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -762,19 +762,13 @@ impl UserFromStorage { } } -impl TryFrom<info::ModuleInfo> for user_role_api::ModuleInfo { - type Error = (); - fn try_from(value: info::ModuleInfo) -> Result<Self, Self::Error> { - let mut permissions = Vec::with_capacity(value.permissions.len()); - for permission in value.permissions { - let permission = permission.try_into()?; - permissions.push(permission); - } - Ok(Self { +impl From<info::ModuleInfo> for user_role_api::ModuleInfo { + fn from(value: info::ModuleInfo) -> Self { + Self { module: value.module.into(), description: value.description, - permissions, - }) + permissions: value.permissions.into_iter().map(Into::into).collect(), + } } } @@ -794,18 +788,17 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule { info::PermissionModule::Files => Self::Files, info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager, info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager, + info::PermissionModule::AccountCreate => Self::AccountCreate, } } } -impl TryFrom<info::PermissionInfo> for user_role_api::PermissionInfo { - type Error = (); - fn try_from(value: info::PermissionInfo) -> Result<Self, Self::Error> { - let enum_name = (&value.enum_name).try_into()?; - Ok(Self { - enum_name, +impl From<info::PermissionInfo> for user_role_api::PermissionInfo { + fn from(value: info::PermissionInfo) -> Self { + Self { + enum_name: value.enum_name.into(), description: value.description, - }) + } } } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index c474a82981b..65ead92ad34 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,7 +1,6 @@ use api_models::user_role as user_role_api; use diesel_models::enums::UserStatus; use error_stack::ResultExt; -use router_env::logger; use crate::{ consts, @@ -44,52 +43,50 @@ pub fn validate_role_id(role_id: &str) -> UserResult<()> { pub fn get_role_name_and_permission_response( role_info: &RoleInfo, ) -> Option<(Vec<user_role_api::Permission>, &'static str)> { - role_info - .get_permissions() - .iter() - .map(TryInto::try_into) - .collect::<Result<Vec<user_role_api::Permission>, _>>() - .ok() - .zip(role_info.get_name()) + role_info.get_name().map(|name| { + ( + role_info + .get_permissions() + .iter() + .map(|&per| per.into()) + .collect::<Vec<user_role_api::Permission>>(), + name, + ) + }) } -impl TryFrom<&Permission> for user_role_api::Permission { - type Error = (); - fn try_from(value: &Permission) -> Result<Self, Self::Error> { +impl From<Permission> for user_role_api::Permission { + fn from(value: Permission) -> Self { match value { - Permission::PaymentRead => Ok(Self::PaymentRead), - Permission::PaymentWrite => Ok(Self::PaymentWrite), - Permission::RefundRead => Ok(Self::RefundRead), - Permission::RefundWrite => Ok(Self::RefundWrite), - Permission::ApiKeyRead => Ok(Self::ApiKeyRead), - Permission::ApiKeyWrite => Ok(Self::ApiKeyWrite), - Permission::MerchantAccountRead => Ok(Self::MerchantAccountRead), - Permission::MerchantAccountWrite => Ok(Self::MerchantAccountWrite), - Permission::MerchantConnectorAccountRead => Ok(Self::MerchantConnectorAccountRead), - Permission::MerchantConnectorAccountWrite => Ok(Self::MerchantConnectorAccountWrite), - Permission::ForexRead => Ok(Self::ForexRead), - Permission::RoutingRead => Ok(Self::RoutingRead), - Permission::RoutingWrite => Ok(Self::RoutingWrite), - Permission::DisputeRead => Ok(Self::DisputeRead), - Permission::DisputeWrite => Ok(Self::DisputeWrite), - Permission::MandateRead => Ok(Self::MandateRead), - Permission::MandateWrite => Ok(Self::MandateWrite), - Permission::CustomerRead => Ok(Self::CustomerRead), - Permission::CustomerWrite => Ok(Self::CustomerWrite), - Permission::FileRead => Ok(Self::FileRead), - Permission::FileWrite => Ok(Self::FileWrite), - Permission::Analytics => Ok(Self::Analytics), - Permission::ThreeDsDecisionManagerWrite => Ok(Self::ThreeDsDecisionManagerWrite), - Permission::ThreeDsDecisionManagerRead => Ok(Self::ThreeDsDecisionManagerRead), - Permission::SurchargeDecisionManagerWrite => Ok(Self::SurchargeDecisionManagerWrite), - Permission::SurchargeDecisionManagerRead => Ok(Self::SurchargeDecisionManagerRead), - Permission::UsersRead => Ok(Self::UsersRead), - Permission::UsersWrite => Ok(Self::UsersWrite), - - Permission::MerchantAccountCreate => { - logger::error!("Invalid use of internal permission"); - Err(()) - } + Permission::PaymentRead => Self::PaymentRead, + Permission::PaymentWrite => Self::PaymentWrite, + Permission::RefundRead => Self::RefundRead, + Permission::RefundWrite => Self::RefundWrite, + Permission::ApiKeyRead => Self::ApiKeyRead, + Permission::ApiKeyWrite => Self::ApiKeyWrite, + Permission::MerchantAccountRead => Self::MerchantAccountRead, + Permission::MerchantAccountWrite => Self::MerchantAccountWrite, + Permission::MerchantConnectorAccountRead => Self::MerchantConnectorAccountRead, + Permission::MerchantConnectorAccountWrite => Self::MerchantConnectorAccountWrite, + Permission::ForexRead => Self::ForexRead, + Permission::RoutingRead => Self::RoutingRead, + Permission::RoutingWrite => Self::RoutingWrite, + Permission::DisputeRead => Self::DisputeRead, + Permission::DisputeWrite => Self::DisputeWrite, + Permission::MandateRead => Self::MandateRead, + Permission::MandateWrite => Self::MandateWrite, + Permission::CustomerRead => Self::CustomerRead, + Permission::CustomerWrite => Self::CustomerWrite, + Permission::FileRead => Self::FileRead, + Permission::FileWrite => Self::FileWrite, + Permission::Analytics => Self::Analytics, + Permission::ThreeDsDecisionManagerWrite => Self::ThreeDsDecisionManagerWrite, + Permission::ThreeDsDecisionManagerRead => Self::ThreeDsDecisionManagerRead, + Permission::SurchargeDecisionManagerWrite => Self::SurchargeDecisionManagerWrite, + Permission::SurchargeDecisionManagerRead => Self::SurchargeDecisionManagerRead, + Permission::UsersRead => Self::UsersRead, + Permission::UsersWrite => Self::UsersWrite, + Permission::MerchantAccountCreate => Self::MerchantAccountCreate, } } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 0d6636e567d..d48aa5f95fe 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -297,6 +297,8 @@ pub enum Flow { ListRoles, /// Get role GetRole, + /// Get role from token + GetRoleFromToken, /// Update user role UpdateUserRole, /// Create merchant account for user in a org
2024-01-18T10:53:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added API to get list of permission user has. <!-- 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 hyperswitch control centre <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? ``` curl --location --request GET '<URL>/user/role' \ --header 'Authorization: Bearer <JWT>' ``` Above API should give an array of permission. All roles and their permission can be found [here](https://github.com/juspay/hyperswitch/blob/main/crates/router/src/services/authorization/predefined_permissions.rs#L28). Example response, ``` [ "PaymentRead", "RefundRead", "ApiKeyRead", "MerchantAccountRead", "MerchantConnectorAccountRead", "RoutingRead", "ForexRead", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerRead", "Analytics", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "UsersRead" ] ``` <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
059e86607dc271c25bb3d23f5adfc7d5f21f62fb
juspay/hyperswitch
juspay__hyperswitch-3387
Bug: [REFACTOR] Add additional field in MandateResponse ### Feature Description Add additional field, `payment_method_response` in MandateResponse ### Possible Implementation Add additional field, `payment_method_response` in MandateResponse ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index d4e11964192..cf25ef195a2 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -131,6 +131,7 @@ host_rs = "" # Rust Locker host mock_locker = true # Emulate a locker locally using Postgres basilisk_host = "" # Basilisk host locker_signing_key_id = "1" # Key_id to sign basilisk hs locker +locker_enabled = true # Boolean to enable or disable saving cards in locker [delayed_session_response] connectors_with_delayed_session_response = "trustpay,payme" # List of connectors which has delayed session response diff --git a/config/development.toml b/config/development.toml index 91269005a0f..b23f68680e6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -69,6 +69,8 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true + [forex_api] call_delay = 21600 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 450fe106a31..8af1528e177 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -56,6 +56,7 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true [jwekey] vault_encryption_key = "" diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 5c0810dc21b..b29f4e0d0c3 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -36,6 +36,8 @@ pub struct MandateResponse { pub payment_method_id: String, /// The payment method pub payment_method: String, + /// The payment method type + pub payment_method_type: Option<String>, /// The card details for mandate pub card: Option<MandateCardDetails>, /// Details about the customer’s acceptance @@ -66,6 +68,15 @@ pub struct MandateCardDetails { #[schema(value_type = Option<String>)] /// A unique identifier alias to identify a particular card pub card_fingerprint: Option<Secret<String>>, + /// The first 6 digits of card + pub card_isin: Option<String>, + /// The bank that issued the card + pub card_issuer: Option<String>, + /// The network that facilitates payment card transactions + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + /// The type of the payment card + pub card_type: Option<String>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 3467777da74..984e6dbffff 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -109,6 +109,19 @@ pub struct CardDetail { /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, + + /// Card Issuing Country + pub card_issuing_country: Option<String>, + + /// Card's Network + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + /// Issuer Bank for Card + pub card_issuer: Option<String>, + + /// Card Type + pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -177,6 +190,12 @@ pub struct CardDetailsPaymentMethod { pub expiry_year: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_network: Option<api_enums::CardNetwork>, + pub card_type: Option<String>, + #[serde(default = "saved_in_locker_default")] + pub saved_to_locker: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] @@ -227,6 +246,18 @@ pub struct CardDetailFromLocker { #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, + + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_type: Option<String>, + pub saved_to_locker: bool, +} + +fn saved_in_locker_default() -> bool { + true } impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { @@ -242,6 +273,11 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, } } } @@ -255,6 +291,11 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, } } } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 42839bf3513..e4a470d0da3 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -54,6 +54,8 @@ impl Default for super::settings::Locker { mock_locker: true, basilisk_host: "localhost".into(), locker_signing_key_id: "1".into(), + //true or false + locker_enabled: true, } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3d93c2f188b..bcf26d63ae8 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -490,6 +490,7 @@ pub struct Locker { pub mock_locker: bool, pub basilisk_host: String, pub locker_signing_key_id: String, + pub locker_enabled: bool, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index e3e308a8a01..4bd2555792a 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -101,6 +101,10 @@ pub async fn call_to_locker( card_exp_year: card.card_exp_year, card_holder_name: card.name_on_card, nick_name: card.nick_name.map(masking::Secret::new), + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, }; let pm_create = api::PaymentMethodCreate { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index aabd846660c..b6837d14f82 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -33,6 +33,7 @@ use crate::{ pub async fn get_mandate( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateResponse> { let mandate = state @@ -42,7 +43,7 @@ pub async fn get_mandate( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( - mandates::MandateResponse::from_db_mandate(&state, mandate).await?, + mandates::MandateResponse::from_db_mandate(&state, key_store, mandate).await?, )) } @@ -202,6 +203,7 @@ pub async fn update_connector_mandate_id( pub async fn get_customer_mandates( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: customers::CustomerId, ) -> RouterResponse<Vec<mandates::MandateResponse>> { let mandates = state @@ -221,7 +223,10 @@ pub async fn get_customer_mandates( } else { let mut response_vec = Vec::with_capacity(mandates.len()); for mandate in mandates { - response_vec.push(mandates::MandateResponse::from_db_mandate(&state, mandate).await?); + response_vec.push( + mandates::MandateResponse::from_db_mandate(&state, key_store.clone(), mandate) + .await?, + ); } Ok(services::ApplicationResponse::Json(response_vec)) } @@ -383,6 +388,7 @@ where pub async fn retrieve_mandates_list( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, constraints: api_models::mandates::MandateListConstraints, ) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> { let mandates = state @@ -392,11 +398,9 @@ pub async fn retrieve_mandates_list( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve mandates")?; - let mandates_list = future::try_join_all( - mandates - .into_iter() - .map(|mandate| mandates::MandateResponse::from_db_mandate(&state, mandate)), - ) + let mandates_list = future::try_join_all(mandates.into_iter().map(|mandate| { + mandates::MandateResponse::from_db_mandate(&state, key_store.clone(), mandate) + })) .await?; Ok(services::ApplicationResponse::Json(mandates_list)) } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 51f54353635..1a8bbcc8ef7 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -558,6 +558,7 @@ pub async fn add_card_hs( req, &merchant_account.merchant_id, ); + Ok(( payment_method_resp, store_card_payload.duplicate.unwrap_or(false), @@ -2508,11 +2509,19 @@ pub async fn list_customer_payment_method( let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let (card, pmd, hyperswitch_token_data) = match pm.payment_method { - enums::PaymentMethod::Card => ( - Some(get_card_details(&pm, key, state).await?), - None, - PaymentTokenData::permanent_card(pm.payment_method_id.clone()), - ), + enums::PaymentMethod::Card => { + let card_details = get_card_details_with_locker_fallback(&pm, key, state).await?; + + if card_details.is_some() { + ( + card_details, + None, + PaymentTokenData::permanent_card(pm.payment_method_id.clone()), + ) + } else { + continue; + } + } #[cfg(feature = "payouts")] enums::PaymentMethod::BankTransfer => { @@ -2571,6 +2580,7 @@ pub async fn list_customer_payment_method( }; //Need validation for enabled payment method ,querying MCA + let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), customer_id: pm.customer_id, @@ -2700,7 +2710,38 @@ pub async fn list_customer_payment_method( Ok(services::ApplicationResponse::Json(response)) } -async fn get_card_details( +pub async fn get_card_details_with_locker_fallback( + pm: &payment_method::PaymentMethod, + key: &[u8], + state: &routes::AppState, +) -> errors::RouterResult<Option<api::CardDetailFromLocker>> { + let card_decrypted = + decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }); + + Ok(if let Some(mut crd) = card_decrypted { + if crd.saved_to_locker { + crd.scheme = pm.scheme.clone(); + Some(crd) + } else { + None + } + } else { + Some(get_card_details_from_locker(state, pm).await?) + }) +} + +pub async fn get_card_details_without_locker_fallback( pm: &payment_method::PaymentMethod, key: &[u8], state: &routes::AppState, @@ -2971,25 +3012,32 @@ impl TempLockerCardSupport { pub async fn retrieve_payment_method( state: routes::AppState, pm: api::PaymentMethodId, + key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { let db = state.store.as_ref(); let pm = db .find_payment_method(&pm.payment_method_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let key = key_store.key.peek(); let card = if pm.payment_method == enums::PaymentMethod::Card { - let card = get_card_from_locker( - &state, - &pm.customer_id, - &pm.merchant_id, - &pm.payment_method_id, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error getting card from card vault")?; - let card_detail = payment_methods::get_card_detail(&pm, card) + let card_detail = if state.conf.locker.locker_enabled { + let card = get_card_from_locker( + &state, + &pm.customer_id, + &pm.merchant_id, + &pm.payment_method_id, + ) + .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting card details from locker")?; + .attach_printable("Error getting card from card vault")?; + payment_methods::get_card_detail(&pm, card) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting card details from locker")? + } else { + get_card_details_without_locker_fallback(&pm, key, &state).await? + }; Some(card_detail) } else { None diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index da4f03b49c1..304091e42ac 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -352,18 +352,26 @@ pub fn mk_add_card_response_hs( req: api::PaymentMethodCreate, merchant_id: &str, ) -> api::PaymentMethodResponse { - let mut card_number = card.card_number.peek().to_owned(); + let card_number = card.card_number.clone(); + let last4_digits = card_number.clone().get_last4(); + let card_isin = card_number.get_card_isin(); + let card = api::CardDetailFromLocker { scheme: None, - last4_digits: Some(card_number.split_off(card_number.len() - 4)), - issuer_country: None, // [#256] bin mapping - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: None, // [#256] - card_fingerprint: None, // fingerprint not send by basilisk-hs need to have this feature in case we need it in future - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, + last4_digits: Some(last4_digits), + issuer_country: None, + card_number: Some(card.card_number.clone()), + expiry_month: Some(card.card_exp_month.clone()), + expiry_year: Some(card.card_exp_year.clone()), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name.clone(), + nick_name: card.nick_name.clone(), + card_isin: Some(card_isin), + card_issuer: card.card_issuer, + card_network: card.card_network, + card_type: card.card_type, + saved_to_locker: true, }; api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), @@ -399,6 +407,11 @@ pub fn mk_add_card_response( card_fingerprint: Some(response.card_fingerprint), card_holder_name: card.card_holder_name, nick_name: card.nick_name, + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, }; api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), @@ -597,6 +610,8 @@ pub fn get_card_detail( ) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> { let card_number = response.card_number; let mut last4_digits = card_number.peek().to_owned(); + //fetch form card bin + let card_detail = api::CardDetailFromLocker { scheme: pm.scheme.to_owned(), issuer_country: pm.issuer_country.clone(), @@ -608,6 +623,11 @@ pub fn get_card_detail( card_fingerprint: None, card_holder_name: response.name_on_card, nick_name: response.nick_name.map(masking::Secret::new), + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, }; Ok(card_detail) } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 07af15a336d..15c79f4b9d9 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -92,7 +92,9 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics - if resp.request.setup_mandate_details.clone().is_some() { + let is_mandate = resp.request.setup_mandate_details.is_some(); + + if is_mandate { let payment_method_id = Box::pin(tokenization::save_payment_method( state, connector, diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 0c03c8ce123..d6343ed871b 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -208,6 +208,7 @@ impl types::SetupMandateRouterData { .to_setup_mandate_failed_response()?; let payment_method_type = self.request.payment_method_type; + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 92dc1bf5f4b..e3a3ccdc02c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -509,16 +509,23 @@ pub async fn get_token_for_recurring_mandate( }; if let diesel_models::enums::PaymentMethod::Card = payment_method.payment_method { - let _ = - cards::get_lookup_key_from_locker(state, &token, &payment_method, merchant_key_store) - .await?; + if state.conf.locker.locker_enabled { + let _ = cards::get_lookup_key_from_locker( + state, + &token, + &payment_method, + merchant_key_store, + ) + .await?; + } + if let Some(payment_method_from_request) = req.payment_method { let pm: storage_enums::PaymentMethod = payment_method_from_request; if pm != payment_method.payment_method { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "payment method in request does not match previously provided payment \ - method information" + method information" .into() }))? } @@ -971,7 +978,6 @@ pub fn payment_intent_status_fsm( None => storage_enums::IntentStatus::RequiresPaymentMethod, } } - pub async fn add_domain_task_to_pt<Op>( operation: &Op, state: &AppState, @@ -1034,6 +1040,10 @@ pub(crate) async fn get_payment_method_create_request( card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), + card_issuing_country: card.card_issuing_country.clone(), + card_network: card.card_network.clone(), + card_issuer: card.card_issuer.clone(), + card_type: card.card_type.clone(), }; let customer_id = customer.customer_id.clone(); let payment_method_request = api::PaymentMethodCreate { @@ -3343,21 +3353,23 @@ pub async fn get_additional_payment_data( }, )) }); - card_info.unwrap_or(api_models::payments::AdditionalPaymentData::Card(Box::new( - api_models::payments::AdditionalCardInfo { - card_issuer: None, - card_network: None, - bank_code: None, - card_type: None, - card_issuing_country: None, - last4, - card_isin, - card_extended_bin, - card_exp_month: Some(card_data.card_exp_month.clone()), - card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: card_data.card_holder_name.clone(), - }, - ))) + card_info.unwrap_or_else(|| { + api_models::payments::AdditionalPaymentData::Card(Box::new( + api_models::payments::AdditionalCardInfo { + card_issuer: None, + card_network: None, + bank_code: None, + card_type: None, + card_issuing_country: None, + last4, + card_isin, + card_extended_bin, + card_exp_month: Some(card_data.card_exp_month.clone()), + card_exp_year: Some(card_data.card_exp_year.clone()), + card_holder_name: card_data.card_holder_name.clone(), + }, + )) + }) } } api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index f884cb79e7e..15d88c94660 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -14,7 +14,7 @@ use crate::{ services, types::{ self, - api::{self, CardDetailsPaymentMethod, PaymentMethodCreateExt}, + api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, storage::enums as storage_enums, }, @@ -74,12 +74,21 @@ where .await?; let merchant_id = &merchant_account.merchant_id; - let locker_response = save_in_locker( - state, - merchant_account, - payment_method_create_request.to_owned(), - ) - .await?; + let locker_response = if !state.conf.locker.locker_enabled { + skip_saving_card_in_locker( + merchant_account, + payment_method_create_request.to_owned(), + ) + .await? + } else { + save_in_locker( + state, + merchant_account, + payment_method_create_request.to_owned(), + ) + .await? + }; + let is_duplicate = locker_response.1; let pm_card_details = locker_response.0.card.as_ref().map(|card| { @@ -168,6 +177,85 @@ where } } +async fn skip_saving_card_in_locker( + merchant_account: &domain::MerchantAccount, + payment_method_request: api::PaymentMethodCreate, +) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { + let merchant_id = &merchant_account.merchant_id; + let customer_id = payment_method_request + .clone() + .customer_id + .clone() + .get_required_value("customer_id")?; + let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + + let last4_digits = payment_method_request + .card + .clone() + .map(|c| c.card_number.get_last4()); + + let card_isin = payment_method_request + .card + .clone() + .map(|c: api_models::payment_methods::CardDetail| c.card_number.get_card_isin()); + + match payment_method_request.card.clone() { + Some(card) => { + let card_detail = CardDetailFromLocker { + scheme: None, + issuer_country: card.card_issuing_country.clone(), + last4_digits: last4_digits.clone(), + card_number: None, + expiry_month: Some(card.card_exp_month.clone()), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_holder_name: card.card_holder_name.clone(), + card_fingerprint: None, + nick_name: None, + card_isin: card_isin.clone(), + card_issuer: card.card_issuer.clone(), + card_network: card.card_network.clone(), + card_type: card.card_type.clone(), + saved_to_locker: false, + }; + let pm_resp = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: Some(card_detail), + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + metadata: None, + created: Some(common_utils::date_time::now()), + bank_transfer: None, + }; + + Ok((pm_resp, false)) + } + None => { + let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + let payment_method_response = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id: pm_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: None, + metadata: None, + created: Some(common_utils::date_time::now()), + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + bank_transfer: None, + }; + Ok((payment_method_response, false)) + } + } +} + pub async fn save_in_locker( state: &AppState, merchant_account: &domain::MerchantAccount, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 56e3a6faf53..1ab24023bdb 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,6 +1,6 @@ use common_utils::{ errors::CustomResult, - ext_traits::{StringExt, ValueExt}, + ext_traits::{AsyncExt, StringExt, ValueExt}, }; use diesel_models::encryption::Encryption; use error_stack::{IntoReport, ResultExt}; @@ -19,6 +19,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, enums as api_enums}, domain::{ @@ -184,6 +185,10 @@ pub async fn save_payout_data_to_locker( card_exp_month: card.expiry_month.to_owned(), card_exp_year: card.expiry_year.to_owned(), nick_name: None, + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, }; let payload = StoreLockerReq::LockerCard(StoreCardReq { merchant_id: &merchant_account.merchant_id, @@ -267,20 +272,65 @@ pub async fn save_payout_data_to_locker( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in saved payout method")?; - let pm_data = api::payment_methods::PaymentMethodsData::Card( - api::payment_methods::CardDetailsPaymentMethod { - last4_digits: card_details - .as_ref() - .map(|c| c.card_number.clone().get_last4()), - issuer_country: None, - expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), - expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), - nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), - card_holder_name: card_details - .as_ref() - .and_then(|c| c.card_holder_name.clone()), - }, - ); + // fetch card info from db + let card_isin = card_details + .as_ref() + .map(|c| c.card_number.clone().get_card_isin()); + + let pm_data = card_isin + .clone() + .async_and_then(|card_isin| async move { + db.get_card_info(&card_isin) + .await + .map_err(|error| services::logger::warn!(card_info_error=?error)) + .ok() + }) + .await + .flatten() + .map(|card_info| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: card_info.card_issuing_country, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: card_info.card_issuer, + card_network: card_info.card_network, + card_type: card_info.card_type, + saved_to_locker: true, + }, + ) + }) + .unwrap_or_else(|| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: None, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, + }, + ) + }); let card_details_encrypted = cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await; diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 4354a3ee195..f291d1cd2e8 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -421,6 +421,7 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: api_models::webhooks::IncomingWebhookEvent, @@ -464,8 +465,12 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandates_response = Box::new( - api::mandates::MandateResponse::from_db_mandate(&state, updated_mandate.clone()) - .await?, + api::mandates::MandateResponse::from_db_mandate( + &state, + key_store, + updated_mandate.clone(), + ) + .await?, ); let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); if let Some(outgoing_event_type) = event_type { @@ -1237,6 +1242,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr state.clone(), merchant_account, business_profile, + key_store, webhook_details, source_verified, event_type, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 2592d8837d5..e7a0804500c 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -226,7 +226,12 @@ pub async fn get_customer_mandates( &req, customer_id, |state, auth, req| { - crate::core::mandate::get_customer_mandates(state, auth.merchant_account, req) + crate::core::mandate::get_customer_mandates( + state, + auth.merchant_account, + auth.key_store, + req, + ) }, auth::auth_type( &auth::ApiKeyAuth, diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index ecc89a10fa2..468d202b94c 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -41,7 +41,7 @@ pub async fn get_mandate( state, &req, mandate_id, - |state, auth, req| mandate::get_mandate(state, auth.merchant_account, req), + |state, auth, req| mandate::get_mandate(state, auth.merchant_account, auth.key_store, req), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) @@ -123,7 +123,9 @@ pub async fn retrieve_mandates_list( state, &req, payload, - |state, auth, req| mandate::retrieve_mandates_list(state, auth.merchant_account, req), + |state, auth, req| { + mandate::retrieve_mandates_list(state, auth.merchant_account, auth.key_store, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::MandateRead), diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index a6eeeabd687..6ef5de886be 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -242,7 +242,7 @@ pub async fn payment_method_retrieve_api( state, &req, payload, - |state, _auth, pm| cards::retrieve_payment_method(state, pm), + |state, auth, pm| cards::retrieve_payment_method(state, pm, auth.key_store), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 8d6b9a15e3a..f6b2d7bba93 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -1,6 +1,7 @@ use api_models::mandates; pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use error_stack::ResultExt; +use masking::PeekInterface; use serde::{Deserialize, Serialize}; use crate::{ @@ -11,7 +12,7 @@ use crate::{ newtype, routes::AppState, types::{ - api, + api, domain, storage::{self, enums as storage_enums}, }, }; @@ -23,12 +24,20 @@ newtype!( #[async_trait::async_trait] pub(crate) trait MandateResponseExt: Sized { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self>; + async fn from_db_mandate( + state: &AppState, + key_store: domain::MerchantKeyStore, + mandate: storage::Mandate, + ) -> RouterResult<Self>; } #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self> { + async fn from_db_mandate( + state: &AppState, + key_store: domain::MerchantKeyStore, + mandate: storage::Mandate, + ) -> RouterResult<Self> { let db = &*state.store; let payment_method = db .find_payment_method(&mandate.payment_method_id) @@ -36,21 +45,35 @@ impl MandateResponseExt for MandateResponse { .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let card = if payment_method.payment_method == storage_enums::PaymentMethod::Card { - let card = payment_methods::cards::get_card_from_locker( - state, - &payment_method.customer_id, - &payment_method.merchant_id, - &payment_method.payment_method_id, - ) - .await?; - let card_detail = payment_methods::transformers::get_card_detail(&payment_method, card) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting card details")?; - Some(MandateCardDetails::from(card_detail).into_inner()) + // if locker is disabled , decrypt the payment method data + let card_details = if state.conf.locker.locker_enabled { + let card = payment_methods::cards::get_card_from_locker( + state, + &payment_method.customer_id, + &payment_method.merchant_id, + &payment_method.payment_method_id, + ) + .await?; + + payment_methods::transformers::get_card_detail(&payment_method, card) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting card details")? + } else { + payment_methods::cards::get_card_details_without_locker_fallback( + &payment_method, + key_store.key.get_inner().peek(), + state, + ) + .await? + }; + + Some(MandateCardDetails::from(card_details).into_inner()) } else { None }; - + let payment_method_type = payment_method + .payment_method_type + .map(|pmt| pmt.to_string()); Ok(Self { mandate_id: mandate.mandate_id, customer_acceptance: Some(api::payments::CustomerAcceptance { @@ -68,6 +91,7 @@ impl MandateResponseExt for MandateResponse { card, status: mandate.mandate_status, payment_method: payment_method.payment_method.to_string(), + payment_method_type, payment_method_id: mandate.payment_method_id, }) } @@ -84,6 +108,10 @@ impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { scheme: card_details_from_locker.scheme, issuer_country: card_details_from_locker.issuer_country, card_fingerprint: card_details_from_locker.card_fingerprint, + card_isin: card_details_from_locker.card_isin, + card_issuer: card_details_from_locker.card_issuer, + card_network: card_details_from_locker.card_network, + card_type: card_details_from_locker.card_type, } .into() } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 358a591a667..268ebd1d3ac 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -33,6 +33,7 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true [forex_api] call_delay = 21600 diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index b2f5d3ea52c..02df6324a06 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4421,11 +4421,37 @@ "description": "Card Holder's Nick Name", "example": "John Doe", "nullable": true + }, + "card_issuing_country": { + "type": "string", + "description": "Card Issuing Country", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "Issuer Bank for Card", + "nullable": true + }, + "card_type": { + "type": "string", + "description": "Card Type", + "nullable": true } } }, "CardDetailFromLocker": { "type": "object", + "required": [ + "saved_to_locker" + ], "properties": { "scheme": { "type": "string", @@ -4462,6 +4488,29 @@ "nick_name": { "type": "string", "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_isin": { + "type": "string", + "nullable": true + }, + "card_issuer": { + "type": "string", + "nullable": true + }, + "card_type": { + "type": "string", + "nullable": true + }, + "saved_to_locker": { + "type": "boolean" } } }, @@ -6884,6 +6933,29 @@ "type": "string", "description": "A unique identifier alias to identify a particular card", "nullable": true + }, + "card_isin": { + "type": "string", + "description": "The first 6 digits of card", + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "The bank that issued the card", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "description": "The type of the payment card", + "nullable": true } } }, @@ -6932,6 +7004,11 @@ "type": "string", "description": "The payment method" }, + "payment_method_type": { + "type": "string", + "description": "The payment method type", + "nullable": true + }, "card": { "allOf": [ {
2024-01-15T11:31:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add locker config to enable or disable locker , so that if the locker is enabled we can store the card_details in the locker else if the config is disabled we don't Also this PR involvesaddition in the `MandateResponse`. ### 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 Feature provides an option for the merchant whether or not to save the card at hyperswitch . Saving the card at hyperswitch is not necessary if the mandate is created at the processor level. ## How did you test it? - Create an MA & MCA - Disable the `locker_enabled` config > Create a Mandate payment , the details will not be stored in Locker and payment will be successful > List PaymentMethods for a Customer won't have any details as the card was never stored > List the Mandates would have mandate details ![Screenshot 2024-01-16 at 4 38 43 PM](https://github.com/juspay/hyperswitch/assets/55580080/c9d5d11b-b31f-4a58-a324-f92c376a7c26) ![Screenshot 2024-01-16 at 4 38 59 PM](https://github.com/juspay/hyperswitch/assets/55580080/32645dfa-c962-43a2-9e7f-ca1056415560) ![Screenshot 2024-01-16 at 4 39 10 PM](https://github.com/juspay/hyperswitch/assets/55580080/f413bd94-b74c-4a1b-bf22-fbc335a05e56) ![Screenshot 2024-01-16 at 4 39 26 PM](https://github.com/juspay/hyperswitch/assets/55580080/2745fabd-bc81-4d2b-ab53-d6829fa53d13) ![Screenshot 2024-01-16 at 4 39 38 PM](https://github.com/juspay/hyperswitch/assets/55580080/25221f1c-7932-4295-9a6e-083355513c15) - Enable the `locker_enabled` config > Create a Mandate payment , the details will be stored in Locker and payment will be successful > List PaymentMethods for a Customer would have details of the card that was stored > List the Mandates ![Screenshot 2024-01-16 at 4 33 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/174a1933-9112-4088-893c-12c4e84b3148) ![Screenshot 2024-01-16 at 4 34 57 PM](https://github.com/juspay/hyperswitch/assets/55580080/2a5f46e7-86b0-470e-89a6-3a8f0a225c3b) ![Screenshot 2024-01-16 at 4 35 18 PM](https://github.com/juspay/hyperswitch/assets/55580080/66a1df1f-0f8a-418e-a122-570508eb97a9) ![Screenshot 2024-01-16 at 4 35 33 PM](https://github.com/juspay/hyperswitch/assets/55580080/8c5fe598-9cad-498f-88eb-ef9ca0c3018b) ![Screenshot 2024-01-16 at 4 35 51 PM](https://github.com/juspay/hyperswitch/assets/55580080/8d05dbcb-ef2d-4c2a-b326-56393ed5b16e) ![Screenshot 2024-01-16 at 4 36 32 PM](https://github.com/juspay/hyperswitch/assets/55580080/0e3e9272-27b5-44de-9c3a-4e1e942faee9) -When we do a list mandates we have an additional field `payment_method_type` ![Screenshot 2024-01-18 at 4 27 53 PM](https://github.com/juspay/hyperswitch/assets/55580080/7b2455e7-889b-4e01-979d-56353ce60f49) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2f693ad1fd857280ef30c6cc0297fb926f0e79e8
juspay/hyperswitch
juspay__hyperswitch-3362
Bug: bug: sample data generation with profile id When trying to generate sample data for users with multiple business profiles, we are getting 500 if the profile id is not passed in the payload.
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index dcf635595e0..3fa2a10629e 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -52,7 +52,7 @@ pub async fn generate_sample_data( let business_label_default = merchant_parsed_details.first().map(|x| x.business.clone()); - let profile_id = crate::core::utils::get_profile_id_from_business_details( + let profile_id = match crate::core::utils::get_profile_id_from_business_details( business_country_default, business_label_default.as_ref(), &merchant_from_db, @@ -61,8 +61,25 @@ pub async fn generate_sample_data( false, ) .await - .change_context(SampleDataError::InternalServerError) - .attach_printable("Failed to get business profile")?; + { + Ok(id) => id.clone(), + Err(error) => { + router_env::logger::error!( + "Profile ID not found in business details. Attempting to fetch from the database {error:?}" + ); + + state + .store + .list_business_profile_by_merchant_id(&merchant_id) + .await + .change_context(SampleDataError::InternalServerError) + .attach_printable("Failed to get business profile")? + .first() + .ok_or(SampleDataError::InternalServerError)? + .profile_id + .clone() + } + }; // 10 percent payments should be failed #[allow(clippy::as_conversions)]
2024-01-16T10:08:50Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Currently for user with multiple business profiles. We are getting 500 if the profile id is not passed in the payload. Therefore, need to fetch the profile_id (the first one) from list of business profiles, for the sample data generation. ### 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 Getting 500, for users with multiple business profiles for sample data generation. ## How did you test it? Singup ``` curl --location 'http://localhost:8080/user/signup' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --data-raw '{ "email": "profile_test@juspay.in", "password": "Test@12345", "country": "IN" }' ``` Creating New business profile: pass current merchant_id for the endpoint ``` curl --location 'http://localhost:8080/account/merchant_1705399107/business_profile' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ "profile_name": "default5" }' ``` Generate Sample Data: ``` curl --location 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` Response will be 200 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5ad3f8939afafce3eec39704dcaa92270b384dcd
juspay/hyperswitch
juspay__hyperswitch-3372
Bug: feat: update user details api
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index c0743c8b8fc..40d082d1cad 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -13,7 +13,8 @@ use crate::user::{ AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest, InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignUpRequest, - SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UserMerchantCreate, VerifyEmailRequest, + SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, + UserMerchantCreate, VerifyEmailRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -54,7 +55,8 @@ common_utils::impl_misc_api_event_type!( InviteUserRequest, InviteUserResponse, VerifyEmailRequest, - SendVerifyEmailRequest + SendVerifyEmailRequest, + UpdateUserAccountDetailsRequest ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index a04c4fef660..8de6a3c0b4f 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -147,3 +147,9 @@ pub struct VerifyTokenResponse { pub merchant_id: String, pub user_email: pii::Email, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct UpdateUserAccountDetailsRequest { + pub name: Option<Secret<String>>, + pub preferred_merchant_id: Option<String>, +} diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index d2f9564a530..6b408038ef5 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -19,6 +19,20 @@ impl UserRole { .await } + pub async fn find_by_user_id_merchant_id( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::user_id + .eq(user_id) + .and(dsl::merchant_id.eq(merchant_id)), + ) + .await + } + pub async fn update_by_user_id_merchant_id( conn: &PgPooledConn, user_id: String, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 131d2b18266..c9887e1770f 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1056,6 +1056,8 @@ diesel::table! { is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, + #[max_length = 64] + preferred_merchant_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index c608f2654c6..84fe8710060 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -19,6 +19,7 @@ pub struct User { pub is_verified: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, + pub preferred_merchant_id: Option<String>, } #[derive( @@ -33,6 +34,7 @@ pub struct UserNew { pub is_verified: bool, pub created_at: Option<PrimitiveDateTime>, pub last_modified_at: Option<PrimitiveDateTime>, + pub preferred_merchant_id: Option<String>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -42,6 +44,7 @@ pub struct UserUpdateInternal { password: Option<Secret<String>>, is_verified: Option<bool>, last_modified_at: PrimitiveDateTime, + preferred_merchant_id: Option<String>, } #[derive(Debug)] @@ -51,6 +54,7 @@ pub enum UserUpdate { name: Option<String>, password: Option<Secret<String>>, is_verified: Option<bool>, + preferred_merchant_id: Option<String>, }, } @@ -63,16 +67,19 @@ impl From<UserUpdate> for UserUpdateInternal { password: None, is_verified: Some(true), last_modified_at, + preferred_merchant_id: None, }, UserUpdate::AccountUpdate { name, password, is_verified, + preferred_merchant_id, } => Self { name, password, is_verified, last_modified_at, + preferred_merchant_id, }, } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 27a4f67618e..729cef65c20 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -253,6 +253,7 @@ pub async fn change_password( name: None, password: Some(new_password_hash), is_verified: None, + preferred_merchant_id: None, }, ) .await @@ -330,6 +331,7 @@ pub async fn reset_password( name: None, password: Some(hash_password), is_verified: Some(true), + preferred_merchant_id: None, }, ) .await @@ -786,3 +788,47 @@ pub async fn verify_token( user_email: user.email, })) } + +pub async fn update_user_details( + state: AppState, + user_token: auth::UserFromToken, + req: user_api::UpdateUserAccountDetailsRequest, +) -> UserResponse<()> { + let user: domain::UserFromStorage = state + .store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let name = req.name.map(domain::UserName::new).transpose()?; + + if let Some(ref preferred_merchant_id) = req.preferred_merchant_id { + let _ = state + .store + .find_user_role_by_user_id_merchant_id(user.get_user_id(), preferred_merchant_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::MerchantIdNotFound) + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + } + + let user_update = storage_user::UserUpdate::AccountUpdate { + name: name.map(|x| x.get_secret().expose()), + password: None, + is_verified: None, + preferred_merchant_id: req.preferred_merchant_id, + }; + + state + .store + .update_user_by_user_id(user.get_user_id(), user_update) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 19a83088a06..8398c153156 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1927,12 +1927,24 @@ impl UserRoleInterface for KafkaStore { ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store.insert_user_role(user_role).await } + async fn find_user_role_by_user_id( &self, user_id: &str, ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store.find_user_role_by_user_id(user_id).await } + + async fn find_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<user_storage::UserRole, errors::StorageError> { + self.diesel_store + .find_user_role_by_user_id_merchant_id(user_id, merchant_id) + .await + } + async fn update_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -1943,9 +1955,11 @@ impl UserRoleInterface for KafkaStore { .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update) .await } + async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { self.diesel_store.delete_user_role(user_id).await } + async fn list_user_roles_by_user_id( &self, user_id: &str, diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index e3dda965f9c..ecd71f7e2c9 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -145,6 +145,7 @@ impl UserInterface for MockDb { is_verified: user_data.is_verified, created_at: user_data.created_at.unwrap_or(time_now), last_modified_at: user_data.created_at.unwrap_or(time_now), + preferred_merchant_id: user_data.preferred_merchant_id, }; users.push(user.clone()); Ok(user) @@ -207,10 +208,14 @@ impl UserInterface for MockDb { name, password, is_verified, + preferred_merchant_id, } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), password: password.clone().unwrap_or(user.password.clone()), is_verified: is_verified.unwrap_or(user.is_verified), + preferred_merchant_id: preferred_merchant_id + .clone() + .or(user.preferred_merchant_id.clone()), ..user.to_owned() }, }; diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index bf84ae134ea..d8938f9683d 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -14,16 +14,25 @@ pub trait UserRoleInterface { &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError>; + async fn find_user_role_by_user_id( &self, user_id: &str, ) -> CustomResult<storage::UserRole, errors::StorageError>; + + async fn find_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<storage::UserRole, errors::StorageError>; + async fn update_user_role_by_user_id_merchant_id( &self, user_id: &str, merchant_id: &str, update: storage::UserRoleUpdate, ) -> CustomResult<storage::UserRole, errors::StorageError>; + async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError>; async fn list_user_roles_by_user_id( @@ -57,6 +66,22 @@ impl UserRoleInterface for Store { .into_report() } + async fn find_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<storage::UserRole, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::UserRole::find_by_user_id_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() + } + async fn update_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -148,6 +173,24 @@ impl UserRoleInterface for MockDb { ) } + async fn find_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<storage::UserRole, errors::StorageError> { + let user_roles = self.user_roles.lock().await; + user_roles + .iter() + .find(|user_role| user_role.user_id == user_id && user_role.merchant_id == merchant_id) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No user role available for user_id = {user_id} and merchant_id = {merchant_id}" + )) + .into(), + ) + } + async fn update_user_role_by_user_id_merchant_id( &self, user_id: &str, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0c489dbe63a..0807fb0800e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -921,6 +921,7 @@ impl User { .service(web::resource("/role/list").route(web::get().to(list_roles))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) .service(web::resource("/user/invite").route(web::post().to(invite_user))) + .service(web::resource("/update").route(web::post().to(update_user_account_details))) .service( web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 12cf76be475..805fb115264 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -178,7 +178,8 @@ impl From<Flow> for ApiIdentifier { | Flow::InviteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmail - | Flow::VerifyEmailRequest => Self::User, + | Flow::VerifyEmailRequest + | Flow::UpdateUserAccountDetails => Self::User, Flow::ListRoles | Flow::GetRole | Flow::UpdateUserRole | Flow::GetAuthorizationInfo => { Self::UserRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 976fd5c9f56..eca32318adf 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -403,3 +403,21 @@ pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpReques )) .await } + +pub async fn update_user_account_details( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::UpdateUserAccountDetailsRequest>, +) -> HttpResponse { + let flow = Flow::UpdateUserAccountDetails; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + user_core::update_user_details, + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 0d6636e567d..c4e0aa3f3ea 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -331,6 +331,8 @@ pub enum Flow { VerifyEmail, /// Send verify email VerifyEmailRequest, + /// Update user account details + UpdateUserAccountDetails, } /// diff --git a/migrations/2024-01-02-111223_users_preferred_merchant_column/down.sql b/migrations/2024-01-02-111223_users_preferred_merchant_column/down.sql new file mode 100644 index 00000000000..b9160b6f105 --- /dev/null +++ b/migrations/2024-01-02-111223_users_preferred_merchant_column/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE users DROP COLUMN preferred_merchant_id; diff --git a/migrations/2024-01-02-111223_users_preferred_merchant_column/up.sql b/migrations/2024-01-02-111223_users_preferred_merchant_column/up.sql new file mode 100644 index 00000000000..77567ce93fa --- /dev/null +++ b/migrations/2024-01-02-111223_users_preferred_merchant_column/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE users ADD COLUMN preferred_merchant_id VARCHAR(64);
2024-01-17T12:44:24Z
## 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 a new column in users table called `preferred_merchant_id`. `preferred_merchant_id` will be used at the time of signin to directly use that `merchant_id` when user has access to multiple merchant accounts. - This PR adds a new API which enables users to update their name and preferred merchant id. ### 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). --> To support the highlighted flow in the following diagram. Note: This PR doesn't have the actual changes of the flow, but has few required changes to make the highlighted flow possible. ```mermaid flowchart TD A["Connect Account"] -- Email --> B{"User Exists"} B -- No --> C["Create new \n Org \n Merchant \n User \n User Role"] C --> D["Send Verify Email"] D --> E["Verify Email Token"] B -- Yes --> D E --> H{"Is there\n any perferred \nmerchant"} F -- ==0 --> I{{"Send list of \nmerchants which\n user has access to\n along with an\n intermediate token"}} F -- >1 --> G[Select the first role with active status] subgraph Preferred Merchant H -- Yes --> M["Send the token \nwith that merchant_id"] end H -- No --> F{"How many \n active merchants\n does user have \naccess to"} I -- merchant_ids, \nintermediate_token --> O["Accept Invite"] O --> P["Change status to active"] P --> G G --> M K["Sign In"] -- Email, Password --> H ``` ## 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)? --> Postman. ```curl curl --location 'http://localhost:8080/user/update' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "name": "user name", // Optional "preferred_merchant_id": "merchant_id" // Optional, user should have access to this merchant_id }' ``` If the api is successful, the db will be updated and the response will be 200 OK. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
eb2a61d8597995838f21b8233653c691118b2191
juspay/hyperswitch
juspay__hyperswitch-3375
Bug: [CI] Add workflow to ensure a pull request contains at least one linked issue ### Description Add a CI workflow to ensure that each pull request contains at least one linked issue. We wish to introduce this requirement for improved project tracking. The workflow should do nothing else: just succeed/fail the check based on the presence/absence of linked issues in a pull request, respectively.
2024-01-17T20:12:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds a new pull request CI check to ensure that all pull requests have at least one linked issue. However, GitHub does not send any webhooks when a pull request is linked with an issue, so the check does not get triggered automatically when an issue is linked for a pull request which is already open. One way to trigger it manually is to update either the pull request title or description/body, and another is to push commits. Since pushing new commits tends to trigger all other checks, editing the pull request description might be preferable in such scenarios. In addition, the PR includes the following changes: - Renames the `conventional-commit-check.yml` workflow file to `pr-convention-checks.yml`. - Removes the workflow code that labelled pull requests whose titles didn't follow conventional commit standards, since we no longer use the label for any purpose nowadays. It was initially added as a means to filter pull requests by that label, when we introduced the check. The pull request can be reviewed one commit at a time for better understanding. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #3375. ## 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)? --> Temporarily modified the trigger to be `pull_request` instead of `pull_request_target` to test the workflow. 1. The check fails if the PR does not contain any linked issues. ![Screenshot of failed check due to absence of linked issues](https://github.com/juspay/hyperswitch/assets/22217505/a8f5a7ac-d96f-4512-ae6d-caf7ae1c0b5c) Link to check run: https://github.com/juspay/hyperswitch/actions/runs/7561263548/job/20589130650?pr=3376 2. The check succeeds if the PR contains at least one linked issue. ![Screenshot of successful check run](https://github.com/juspay/hyperswitch/assets/22217505/779214c3-4552-463d-8dbd-34f8a403c41f) Link to check run: https://github.com/juspay/hyperswitch/actions/runs/7561509816/job/20589902417?pr=3376 3. The check fails if any of the linked issues is closed. ![Screenshot of failed check run due to one of the issues being closed](https://github.com/juspay/hyperswitch/assets/22217505/2b4b1b44-8978-4cf4-96c6-54c23a223380) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
eb2a61d8597995838f21b8233653c691118b2191
juspay/hyperswitch
juspay__hyperswitch-3366
Bug: feat(invite): make accept invite api
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index aa8d13dab6d..c8d8fd96a7a 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -1,8 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ - AuthorizationInfoResponse, GetRoleRequest, ListRolesResponse, RoleInfoResponse, - UpdateUserRoleRequest, + AcceptInvitationRequest, AuthorizationInfoResponse, GetRoleRequest, ListRolesResponse, + RoleInfoResponse, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( @@ -10,5 +10,6 @@ common_utils::impl_misc_api_event_type!( RoleInfoResponse, GetRoleRequest, AuthorizationInfoResponse, - UpdateUserRoleRequest + UpdateUserRoleRequest, + AcceptInvitationRequest ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index b057f8ca8bc..d2548935f62 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,3 +1,5 @@ +use crate::user::DashboardEntryResponse; + #[derive(Debug, serde::Serialize)] pub struct ListRolesResponse(pub Vec<RoleInfoResponse>); @@ -91,3 +93,11 @@ pub enum UserStatus { Active, InvitationSent, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct AcceptInvitationRequest { + pub merchant_ids: Vec<String>, + pub need_dashboard_entry_response: Option<bool>, +} + +pub type AcceptInvitationResponse = DashboardEntryResponse; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 729cef65c20..3384e229009 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -90,11 +90,10 @@ pub async fn signup( UserStatus::Active, ) .await?; - let token = - utils::user::generate_jwt_auth_token(state.clone(), &user_from_db, &user_role).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(state, user_from_db, user_role, token)?, + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, )) } @@ -118,11 +117,10 @@ pub async fn signin( user_from_db.compare_password(request.password)?; let user_role = user_from_db.get_role_from_db(state.clone()).await?; - let token = - utils::user::generate_jwt_auth_token(state.clone(), &user_from_db, &user_role).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(state, user_from_db, user_role, token)?, + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, )) } @@ -600,7 +598,7 @@ pub async fn switch_merchant_id( .ok_or(UserErrors::InvalidRoleOperation.into()) .attach_printable("User doesn't have access to switch")?; - let token = utils::user::generate_jwt_auth_token(state, &user, user_role).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user, user_role).await?; (token, user_role.role_id.clone()) }; @@ -712,11 +710,10 @@ pub async fn verify_email( let user_from_db: domain::UserFromStorage = user.into(); let user_role = user_from_db.get_role_from_db(state.clone()).await?; - let token = - utils::user::generate_jwt_auth_token(state.clone(), &user_from_db, &user_role).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(state, user_from_db, user_role, token)?, + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, )) } diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index d8ff836e1f8..245f8d246d2 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,6 +1,7 @@ use api_models::user_role as user_role_api; -use diesel_models::user_role::UserRoleUpdate; +use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate}; use error_stack::ResultExt; +use router_env::logger; use crate::{ core::errors::{UserErrors, UserResponse}, @@ -115,3 +116,48 @@ pub async fn update_user_role( Ok(ApplicationResponse::StatusOk) } + +pub async fn accept_invitation( + state: AppState, + user_token: auth::UserWithoutMerchantFromToken, + req: user_role_api::AcceptInvitationRequest, +) -> UserResponse<user_role_api::AcceptInvitationResponse> { + let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async { + state + .store + .update_user_role_by_user_id_merchant_id( + user_token.user_id.as_str(), + merchant_id, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user_token.user_id.clone(), + }, + ) + .await + .map_err(|e| { + logger::error!("Error while accepting invitation {}", e); + }) + .ok() + })) + .await + .into_iter() + .reduce(Option::or) + .flatten() + .ok_or(UserErrors::MerchantIdNotFound)?; + + if let Some(true) = req.need_dashboard_entry_response { + let user_from_db = state + .store + .find_user_by_id(user_token.user_id.as_str()) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + return Ok(ApplicationResponse::Json( + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, + )); + } + + Ok(ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 3d63df2fe80..4345109a672 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -922,6 +922,7 @@ impl User { .service(web::resource("/role").route(web::get().to(get_role_from_token))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) .service(web::resource("/user/invite").route(web::post().to(invite_user))) + .service(web::resource("/user/invite/accept").route(web::post().to(accept_invitation))) .service(web::resource("/update").route(web::post().to(update_user_account_details))) .service( web::resource("/data") diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index d3a2e1af9a7..1c967222dc7 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -185,7 +185,8 @@ impl From<Flow> for ApiIdentifier { | Flow::GetRole | Flow::GetRoleFromToken | Flow::UpdateUserRole - | Flow::GetAuthorizationInfo => Self::UserRole, + | Flow::GetAuthorizationInfo + | Flow::AcceptInvitation => Self::UserRole, Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index fe305942d03..73b1ef1b01d 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -96,3 +96,22 @@ pub async fn update_user_role( )) .await } + +pub async fn accept_invitation( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_role_api::AcceptInvitationRequest>, +) -> HttpResponse { + let flow = Flow::AcceptInvitation; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload, + user_role_core::accept_invitation, + &auth::UserWithoutMerchantJWTAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 3370912394e..eaadc0d5c7b 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -55,6 +55,9 @@ pub enum AuthenticationType { merchant_id: String, user_id: Option<String>, }, + UserJwt { + user_id: String, + }, MerchantId { merchant_id: String, }, @@ -81,11 +84,32 @@ impl AuthenticationType { user_id: _, } | Self::WebhookAuth { merchant_id } => Some(merchant_id.as_ref()), - Self::AdminApiKey | Self::NoAuth => None, + Self::AdminApiKey | Self::UserJwt { .. } | Self::NoAuth => None, } } } +#[derive(Clone, Debug)] +pub struct UserWithoutMerchantFromToken { + pub user_id: String, +} + +#[derive(serde::Serialize, serde::Deserialize)] +pub struct UserAuthToken { + pub user_id: String, + pub exp: u64, +} + +#[cfg(feature = "olap")] +impl UserAuthToken { + pub async fn new_token(user_id: String, settings: &settings::Settings) -> UserResult<String> { + let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); + let exp = jwt::generate_exp(exp_duration)?.as_secs(); + let token_payload = Self { user_id, exp }; + jwt::generate_jwt(&token_payload, settings).await + } +} + #[derive(serde::Serialize, serde::Deserialize)] pub struct AuthToken { pub user_id: String, @@ -276,6 +300,33 @@ pub async fn get_admin_api_key( .await } +#[derive(Debug)] +pub struct UserWithoutMerchantJWTAuth; + +#[cfg(feature = "olap")] +#[async_trait] +impl<A> AuthenticateAndFetch<UserWithoutMerchantFromToken, A> for UserWithoutMerchantJWTAuth +where + A: AppStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(UserWithoutMerchantFromToken, AuthenticationType)> { + let payload = parse_jwt_payload::<A, UserAuthToken>(request_headers, state).await?; + + Ok(( + UserWithoutMerchantFromToken { + user_id: payload.user_id.clone(), + }, + AuthenticationType::UserJwt { + user_id: payload.user_id, + }, + )) + } +} + #[derive(Debug)] pub struct AdminApiAuth; diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 53c88f8aea1..bbe21f289aa 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -739,7 +739,7 @@ impl UserFromStorage { } #[cfg(feature = "email")] - pub fn get_verification_days_left(&self, state: AppState) -> UserResult<Option<i64>> { + pub fn get_verification_days_left(&self, state: &AppState) -> UserResult<Option<i64>> { if self.0.is_verified { return Ok(None); } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index a115fa2a2d8..a3f9e7978aa 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -56,7 +56,7 @@ impl UserFromToken { } pub async fn generate_jwt_auth_token( - state: AppState, + state: &AppState, user: &UserFromStorage, user_role: &UserRole, ) -> UserResult<Secret<String>> { @@ -89,17 +89,13 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes( Ok(Secret::new(token)) } -#[allow(unused_variables)] pub fn get_dashboard_entry_response( - state: AppState, + state: &AppState, user: UserFromStorage, user_role: UserRole, token: Secret<String>, ) -> UserResult<user_api::DashboardEntryResponse> { - #[cfg(feature = "email")] - let verification_days_left = user.get_verification_days_left(state)?; - #[cfg(not(feature = "email"))] - let verification_days_left = None; + let verification_days_left = get_verification_days_left(state, &user)?; Ok(user_api::DashboardEntryResponse { merchant_id: user_role.merchant_id, @@ -111,3 +107,14 @@ pub fn get_dashboard_entry_response( user_role: user_role.role_id, }) } + +#[allow(unused_variables)] +pub fn get_verification_days_left( + state: &AppState, + user: &UserFromStorage, +) -> UserResult<Option<i64>> { + #[cfg(feature = "email")] + return user.get_verification_days_left(state); + #[cfg(not(feature = "email"))] + return Ok(None); +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 7e3a692517f..ba323ebc5e3 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -335,6 +335,8 @@ pub enum Flow { VerifyEmailRequest, /// Update user account details UpdateUserAccountDetails, + /// Accept user invitation + AcceptInvitation, } ///
2024-01-17T07:14:02Z
## 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 add a new API for accepting invitation and also a new JWT auth type which has only `user_id`. ### 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). --> To support the Accept Invite flow in the following flow. ```mermaid flowchart TD A["Connect Account"] -- Email --> B{"User Exists"} B -- No --> C["Create new \n Org \n Merchant \n User \n User Role"] C --> D["Send Verify Email"] D --> E["Verify Email Token"] B -- Yes --> D E --> H{"Is there\n any perferred \nmerchant"} F -- ==0 --> I{{"Send list of \nmerchants which\n user has access to\n along with an\n intermediate token"}} F -- >1 --> G[Select the first role with active status] H -- Yes --> M["Send the token \nwith that merchant_id"] H -- No --> F{"How many \n active merchants\n does user have \naccess to"} I -- merchant_ids, \nintermediate_token --> O["Accept Invite"] subgraph Accept Invite O --> P["Change status to active"] P --> G G --> M end K["Sign In"] -- Email, Password --> H ``` ## 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 curl --location 'http://localhost:8080/user/user/invite/accept' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "merchant_ids": [ "merchant_id1", "merchant_id2", "merchant_id3" ], "need_dashboard_entry_response": true }' ``` If any of the `merchant_id` status is `active`, then you will be getting the following response. ``` { "token": "JWT with merchant_id, user_id, user_role", "merchant_id": "merchant_id", "name": "user name", "email": "user email", "verification_days_left": null, "user_role": "user role" } ``` If `need_dashboard_entry_response` is `false` or not sent, then the response will be 200 OK. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1c04ac751240f5c931df0f282af1e0ad745e9509
juspay/hyperswitch
juspay__hyperswitch-3359
Bug: [FEATURE] Recon APIs ### Feature Description Add recon related APIs in HyperSwitch for managing recon module for the consumers. Recon dashboard is a separate application hosted at https://sandbox.hyperswitch.io/recon-dashboard/ Recon module in HyperSwitch should be able to perform below tasks - Toggle recon module for a given merchant - Generate tokens for Recon dashboard login - Let admins modify the state of recon related stuff for a given merchant - Verify the generated token ### Possible Implementation Below endpoints are exposed for performing the required tasks - `/recon/update_merchant` - admin API call for updating any recon related field for a given merchant. - `/recon/token` - request a token for an user which is used for logging into Recon's dashboard. - `/recon/request` - let's user send a mail to HS team for enabling recon for their merchant's account. - `/recon/verify_token` - validate a generated token. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 69980361500..45702a4ecb0 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license.workspace = true [features] -default = ["payouts", "frm"] +default = ["payouts", "frm", "recon"] business_profile_routing = [] connector_choice_bcompat = [] errors = ["dep:actix-web", "dep:reqwest"] @@ -18,6 +18,7 @@ dummy_connector = ["euclid/dummy_connector", "common_enums/dummy_connector"] detailed_errors = [] payouts = [] frm = [] +recon = [] [dependencies] actix-web = { version = "4.3.1", optional = true } diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 6d9bd5db342..26a9d222d6b 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -5,6 +5,8 @@ mod locker_migration; pub mod payment; #[cfg(feature = "payouts")] pub mod payouts; +#[cfg(feature = "recon")] +pub mod recon; pub mod refund; pub mod routing; pub mod user; diff --git a/crates/api_models/src/events/recon.rs b/crates/api_models/src/events/recon.rs new file mode 100644 index 00000000000..aed648f4c86 --- /dev/null +++ b/crates/api_models/src/events/recon.rs @@ -0,0 +1,21 @@ +use common_utils::events::{ApiEventMetric, ApiEventsType}; + +use crate::recon::{ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest}; + +impl ApiEventMetric for ReconUpdateMerchantRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Recon) + } +} + +impl ApiEventMetric for ReconTokenResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Recon) + } +} + +impl ApiEventMetric for ReconStatusResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Recon) + } +} diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 1f4cb7359c7..c0743c8b8fc 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -1,7 +1,11 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; +#[cfg(feature = "recon")] +use masking::PeekInterface; #[cfg(feature = "dummy_connector")] use crate::user::sample_data::SampleDataRequest; +#[cfg(feature = "recon")] +use crate::user::VerifyTokenResponse; use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, @@ -21,6 +25,16 @@ impl ApiEventMetric for DashboardEntryResponse { } } +#[cfg(feature = "recon")] +impl ApiEventMetric for VerifyTokenResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::User { + merchant_id: self.merchant_id.clone(), + user_id: self.user_email.peek().to_string(), + }) + } +} + common_utils::impl_misc_api_event_type!( SignUpRequest, SignUpWithMerchantIdRequest, diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index dc1f6eb6537..1ea79ff6fe8 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -26,6 +26,8 @@ pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod pm_auth; +#[cfg(feature = "recon")] +pub mod recon; pub mod refunds; pub mod routing; pub mod surcharge_decision_configs; diff --git a/crates/api_models/src/recon.rs b/crates/api_models/src/recon.rs new file mode 100644 index 00000000000..efbe28f96ba --- /dev/null +++ b/crates/api_models/src/recon.rs @@ -0,0 +1,21 @@ +use common_utils::pii; +use masking::Secret; + +use crate::enums; + +#[derive(serde::Deserialize, Debug, serde::Serialize)] +pub struct ReconUpdateMerchantRequest { + pub merchant_id: String, + pub recon_status: enums::ReconStatus, + pub user_email: pii::Email, +} + +#[derive(Debug, serde::Serialize)] +pub struct ReconTokenResponse { + pub token: Secret<String>, +} + +#[derive(Debug, serde::Serialize)] +pub struct ReconStatusResponse { + pub recon_status: enums::ReconStatus, +} diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index f5af31c8e7f..a04c4fef660 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -140,3 +140,10 @@ pub struct UserMerchantAccount { pub merchant_id: String, pub merchant_name: OptionalEncryptableName, } + +#[cfg(feature = "recon")] +#[derive(serde::Serialize, Debug)] +pub struct VerifyTokenResponse { + pub merchant_id: String, + pub user_email: pii::Email, +} diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 6bbf78afe42..c2bf50d96c3 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -49,6 +49,7 @@ pub enum ApiEventsType { Miscellaneous, RustLocker, FraudCheck, + Recon, } impl ApiEventMetric for serde_json::Value {} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 8ecac362091..0a544e0bd09 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -9,7 +9,7 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] +default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm", "recon"] s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config", "olap"] @@ -30,6 +30,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect external_access_dc = ["dummy_connector"] detailed_errors = ["api_models/detailed_errors", "error-stack/serde"] payouts = [] +recon = ["email"] retry = [] [dependencies] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b1a582cedec..27a4f67618e 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -757,3 +757,32 @@ pub async fn send_verification_mail( Ok(ApplicationResponse::StatusOk) } + +#[cfg(feature = "recon")] +pub async fn verify_token( + state: AppState, + req: auth::ReconUser, +) -> UserResponse<user_api::VerifyTokenResponse> { + let user = state + .store + .find_user_by_id(&req.user_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::UserNotFound) + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + let merchant_id = state + .store + .find_user_role_by_user_id(&req.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .merchant_id; + + Ok(ApplicationResponse::Json(user_api::VerifyTokenResponse { + merchant_id: merchant_id.to_string(), + user_email: user.email, + })) +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 696198f2153..c38a4dc85b5 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -165,6 +165,12 @@ pub fn mk_app( { server_app = server_app.service(routes::StripeApis::server(state.clone())); } + + #[cfg(feature = "recon")] + { + server_app = server_app.service(routes::Recon::server(state.clone())); + } + server_app = server_app.service(routes::Cards::server(state.clone())); server_app = server_app.service(routes::Cache::server(state.clone())); server_app = server_app.service(routes::Health::server(state)); diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index d4bfabb6f92..d9916f98e74 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -28,6 +28,8 @@ pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; +#[cfg(feature = "recon")] +pub mod recon; pub mod refunds; #[cfg(feature = "olap")] pub mod routing; @@ -53,6 +55,8 @@ pub use self::app::DummyConnector; pub use self::app::Forex; #[cfg(feature = "payouts")] pub use self::app::Payouts; +#[cfg(all(feature = "olap", feature = "recon"))] +pub use self::app::Recon; #[cfg(all(feature = "olap", feature = "kms"))] pub use self::app::Verify; pub use self::app::{ diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 77253d1d75c..0c489dbe63a 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -40,6 +40,8 @@ use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*}; use super::{ephemeral_key::*, payment_methods::*, webhooks::*}; #[cfg(all(feature = "frm", feature = "oltp"))] use crate::routes::fraud_check as frm_routes; +#[cfg(all(feature = "recon", feature = "olap"))] +use crate::routes::recon as recon_routes; #[cfg(feature = "olap")] use crate::routes::verify_connector::payment_connector_verify; pub use crate::{ @@ -568,6 +570,26 @@ impl PaymentMethods { } } +#[cfg(all(feature = "olap", feature = "recon"))] +pub struct Recon; + +#[cfg(all(feature = "olap", feature = "recon"))] +impl Recon { + pub fn server(state: AppState) -> Scope { + web::scope("/recon") + .app_data(web::Data::new(state)) + .service( + web::resource("/update_merchant") + .route(web::post().to(recon_routes::update_merchant)), + ) + .service(web::resource("/token").route(web::get().to(recon_routes::get_recon_token))) + .service( + web::resource("/request").route(web::post().to(recon_routes::request_for_recon)), + ) + .service(web::resource("/verify_token").route(web::get().to(verify_recon_token))) + } +} + #[cfg(feature = "olap")] pub struct Blocklist; diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index c560f0d988a..12cf76be475 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -31,6 +31,7 @@ pub enum ApiIdentifier { User, UserRole, ConnectorOnboarding, + Recon, } impl From<Flow> for ApiIdentifier { @@ -186,6 +187,11 @@ impl From<Flow> for ApiIdentifier { Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding } + + Flow::ReconMerchantUpdate + | Flow::ReconTokenRequest + | Flow::ReconServiceRequest + | Flow::ReconVerifyToken => Self::Recon, } } } diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs new file mode 100644 index 00000000000..d34e30237dd --- /dev/null +++ b/crates/router/src/routes/recon.rs @@ -0,0 +1,250 @@ +use actix_web::{web, HttpRequest, HttpResponse}; +use api_models::recon as recon_api; +use common_enums::ReconStatus; +use error_stack::ResultExt; +use masking::{ExposeInterface, PeekInterface, Secret}; +use router_env::Flow; + +use super::AppState; +use crate::{ + core::{ + api_locking, + errors::{self, RouterResponse, RouterResult, StorageErrorExt, UserErrors}, + }, + services::{ + api as service_api, api, + authentication::{self as auth, ReconUser, UserFromToken}, + email::types as email_types, + recon::ReconToken, + }, + types::{ + api::{self as api_types, enums}, + domain::{UserEmail, UserFromStorage, UserName}, + storage, + }, +}; + +pub async fn update_merchant( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<recon_api::ReconUpdateMerchantRequest>, +) -> HttpResponse { + let flow = Flow::ReconMerchantUpdate; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _user, req| recon_merchant_account_update(state, req), + &auth::ReconAdmin, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { + let flow = Flow::ReconServiceRequest; + Box::pin(api::server_wrap( + flow, + state, + &http_req, + (), + |state, user: UserFromToken, _req| send_recon_request(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::ReconTokenRequest; + Box::pin(api::server_wrap( + flow, + state, + &req, + (), + |state, user: ReconUser, _| generate_recon_token(state, user), + &auth::ReconJWT, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn send_recon_request( + state: AppState, + user: UserFromToken, +) -> RouterResponse<recon_api::ReconStatusResponse> { + let db = &*state.store; + let user_from_db = db + .find_user_by_id(&user.user_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let merchant_id = db + .find_user_role_by_user_id(&user.user_id) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)? + .merchant_id; + let key_store = db + .get_merchant_key_store_by_merchant_id( + merchant_id.as_str(), + &db.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + let merchant_account = db + .find_merchant_account_by_merchant_id(merchant_id.as_str(), &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let email_contents = email_types::ProFeatureRequest { + feature_name: "RECONCILIATION & SETTLEMENT".to_string(), + merchant_id: merchant_id.clone(), + user_name: UserName::new(user_from_db.name) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to form username")?, + recipient_email: UserEmail::from_pii_email(user_from_db.email.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert to UserEmail from pii::Email")?, + settings: state.conf.clone(), + subject: format!( + "Dashboard Pro Feature Request by {}", + user_from_db.email.expose().peek() + ), + }; + + let is_email_sent = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to compose and send email for ProFeatureRequest") + .is_ok(); + + if is_email_sent { + let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { + recon_status: enums::ReconStatus::Requested, + }; + + let response = db + .update_merchant(merchant_account, updated_merchant_account, &key_store) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!("Failed while updating merchant's recon status: {merchant_id}") + })?; + + Ok(service_api::ApplicationResponse::Json( + recon_api::ReconStatusResponse { + recon_status: response.recon_status, + }, + )) + } else { + Ok(service_api::ApplicationResponse::Json( + recon_api::ReconStatusResponse { + recon_status: enums::ReconStatus::NotRequested, + }, + )) + } +} + +pub async fn recon_merchant_account_update( + state: AppState, + req: recon_api::ReconUpdateMerchantRequest, +) -> RouterResponse<api_types::MerchantAccountResponse> { + let merchant_id = &req.merchant_id.clone(); + let user_email = &req.user_email.clone(); + + let db = &*state.store; + + let key_store = db + .get_merchant_key_store_by_merchant_id( + &req.merchant_id, + &db.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_account = db + .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { + recon_status: req.recon_status, + }; + + let response = db + .update_merchant(merchant_account, updated_merchant_account, &key_store) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!("Failed while updating merchant's recon status: {merchant_id}") + })?; + + let email_contents = email_types::ReconActivation { + recipient_email: UserEmail::from_pii_email(user_email.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert to UserEmail from pii::Email")?, + user_name: UserName::new(Secret::new("HyperSwitch User".to_string())) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to form username")?, + settings: state.conf.clone(), + subject: "Approval of Recon Request - Access Granted to Recon Dashboard", + }; + + if req.recon_status == ReconStatus::Active { + let _is_email_sent = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to compose and send email for ReconActivation") + .is_ok(); + } + + Ok(service_api::ApplicationResponse::Json( + response + .try_into() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "merchant_account", + })?, + )) +} + +pub async fn generate_recon_token( + state: AppState, + req: ReconUser, +) -> RouterResponse<recon_api::ReconTokenResponse> { + let db = &*state.store; + let user = db + .find_user_by_id(&req.user_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(errors::ApiErrorResponse::InvalidJwtToken) + } else { + e.change_context(errors::ApiErrorResponse::InternalServerError) + } + })? + .into(); + + let token = Box::pin(get_recon_auth_token(user, state)) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + Ok(service_api::ApplicationResponse::Json( + recon_api::ReconTokenResponse { token }, + )) +} + +pub async fn get_recon_auth_token( + user: UserFromStorage, + state: AppState, +) -> RouterResult<Secret<String>> { + ReconToken::new_token(user.0.user_id.clone(), &state.conf).await +} diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index a77b82c550e..976fd5c9f56 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -388,3 +388,18 @@ pub async fn verify_email_request( )) .await } + +#[cfg(feature = "recon")] +pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { + let flow = Flow::ReconVerifyToken; + Box::pin(api::server_wrap( + flow, + state.clone(), + &http_req, + (), + |state, user, _req| user_core::verify_token(state, user), + &auth::ReconJWT, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 57f3b802bd5..8c973105d53 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -7,6 +7,8 @@ pub mod jwt; pub mod kafka; pub mod logger; pub mod pm_auth; +#[cfg(feature = "recon")] +pub mod recon; #[cfg(feature = "email")] pub mod email; diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index b48465ebd17..3370912394e 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -12,10 +12,14 @@ use serde::Serialize; use super::authorization::{self, permissions::Permission}; #[cfg(feature = "olap")] use super::jwt; +#[cfg(feature = "recon")] +use super::recon::ReconToken; #[cfg(feature = "olap")] use crate::consts; #[cfg(feature = "olap")] use crate::core::errors::UserResult; +#[cfg(feature = "recon")] +use crate::routes::AppState; use crate::{ configs::settings, core::{ @@ -822,3 +826,95 @@ where } default_auth } + +#[cfg(feature = "recon")] +static RECON_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = + tokio::sync::OnceCell::const_new(); + +#[cfg(feature = "recon")] +pub async fn get_recon_admin_api_key( + secrets: &settings::Secrets, + #[cfg(feature = "kms")] kms_client: &kms::KmsClient, +) -> RouterResult<&'static StrongSecret<String>> { + RECON_API_KEY + .get_or_try_init(|| async { + #[cfg(feature = "kms")] + let recon_admin_api_key = secrets + .kms_encrypted_recon_admin_api_key + .decrypt_inner(kms_client) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to KMS decrypt recon admin API key")?; + + #[cfg(not(feature = "kms"))] + let recon_admin_api_key = secrets.recon_admin_api_key.clone(); + + Ok(StrongSecret::new(recon_admin_api_key)) + }) + .await +} + +#[cfg(feature = "recon")] +pub struct ReconAdmin; + +#[async_trait] +#[cfg(feature = "recon")] +impl<A> AuthenticateAndFetch<(), A> for ReconAdmin +where + A: AppStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let request_admin_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + let conf = state.conf(); + + let admin_api_key = get_recon_admin_api_key( + &conf.secrets, + #[cfg(feature = "kms")] + kms::get_kms_client(&conf.kms).await, + ) + .await?; + + if request_admin_api_key != admin_api_key.peek() { + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Recon Admin Authentication Failure"))?; + } + + Ok(((), AuthenticationType::NoAuth)) + } +} + +#[cfg(feature = "recon")] +pub struct ReconJWT; +#[cfg(feature = "recon")] +pub struct ReconUser { + pub user_id: String, +} +#[cfg(feature = "recon")] +impl AuthInfo for ReconUser { + fn get_merchant_id(&self) -> Option<&str> { + None + } +} +#[cfg(all(feature = "olap", feature = "recon"))] +#[async_trait] +impl AuthenticateAndFetch<ReconUser, AppState> for ReconJWT { + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &AppState, + ) -> RouterResult<(ReconUser, AuthenticationType)> { + let payload = parse_jwt_payload::<AppState, ReconToken>(request_headers, state).await?; + + Ok(( + ReconUser { + user_id: payload.user_id, + }, + AuthenticationType::NoAuth, + )) + } +} diff --git a/crates/router/src/services/email/assets/recon_activated.html b/crates/router/src/services/email/assets/recon_activation.html similarity index 100% rename from crates/router/src/services/email/assets/recon_activated.html rename to crates/router/src/services/email/assets/recon_activation.html diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index d5c28b1fd6a..0ef15eaa40d 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,17 +1,37 @@ use common_utils::errors::CustomResult; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; -use masking::ExposeInterface; +use masking::{ExposeInterface, PeekInterface}; use crate::{configs, consts}; #[cfg(feature = "olap")] use crate::{core::errors::UserErrors, services::jwt, types::domain}; pub enum EmailBody { - Verify { link: String }, - Reset { link: String, user_name: String }, - MagicLink { link: String, user_name: String }, - InviteUser { link: String, user_name: String }, + Verify { + link: String, + }, + Reset { + link: String, + user_name: String, + }, + MagicLink { + link: String, + user_name: String, + }, + InviteUser { + link: String, + user_name: String, + }, + ReconActivation { + user_name: String, + }, + ProFeatureRequest { + feature_name: String, + merchant_id: String, + user_name: String, + user_email: String, + }, } pub mod html { @@ -43,6 +63,30 @@ pub mod html { link = link ) } + EmailBody::ReconActivation { user_name } => { + format!( + include_str!("assets/recon_activation.html"), + username = user_name, + ) + } + EmailBody::ProFeatureRequest { + feature_name, + merchant_id, + user_name, + user_email, + } => { + format!( + "Dear Hyperswitch Support Team, + + Dashboard Pro Feature Request, + Feature name : {feature_name} + Merchant ID : {merchant_id} + Merchant Name : {user_name} + Email : {user_email} + + (note: This is an auto generated email. use merchant email for any further comunications)", + ) + } } } } @@ -198,3 +242,54 @@ impl EmailData for InviteUser { }) } } + +pub struct ReconActivation { + pub recipient_email: domain::UserEmail, + pub user_name: domain::UserName, + pub settings: std::sync::Arc<configs::settings::Settings>, + pub subject: &'static str, +} + +#[async_trait::async_trait] +impl EmailData for ReconActivation { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let body = html::get_html_body(EmailBody::ReconActivation { + user_name: self.user_name.clone().get_secret().expose(), + }); + + Ok(EmailContents { + subject: self.subject.to_string(), + body: external_services::email::IntermediateString::new(body), + recipient: self.recipient_email.clone().into_inner(), + }) + } +} + +pub struct ProFeatureRequest { + pub recipient_email: domain::UserEmail, + pub feature_name: String, + pub merchant_id: String, + pub user_name: domain::UserName, + pub settings: std::sync::Arc<configs::settings::Settings>, + pub subject: String, +} + +#[async_trait::async_trait] +impl EmailData for ProFeatureRequest { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let recipient = self.recipient_email.clone().into_inner(); + + let body = html::get_html_body(EmailBody::ProFeatureRequest { + user_name: self.user_name.clone().get_secret().expose(), + feature_name: self.feature_name.clone(), + merchant_id: self.merchant_id.clone(), + user_email: recipient.peek().to_string(), + }); + + Ok(EmailContents { + subject: self.subject.clone(), + body: external_services::email::IntermediateString::new(body), + recipient, + }) + } +} diff --git a/crates/router/src/services/recon.rs b/crates/router/src/services/recon.rs new file mode 100644 index 00000000000..d5a2151a487 --- /dev/null +++ b/crates/router/src/services/recon.rs @@ -0,0 +1,29 @@ +use error_stack::ResultExt; +use masking::Secret; + +use super::jwt; +use crate::{ + consts, + core::{self, errors::RouterResult}, + routes::app::settings::Settings, +}; + +#[derive(serde::Serialize, serde::Deserialize)] +pub struct ReconToken { + pub user_id: String, + pub exp: u64, +} + +impl ReconToken { + pub async fn new_token(user_id: String, settings: &Settings) -> RouterResult<Secret<String>> { + let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); + let exp = jwt::generate_exp(exp_duration) + .change_context(core::errors::ApiErrorResponse::InternalServerError)? + .as_secs(); + let token_payload = Self { user_id, exp }; + let token = jwt::generate_jwt(&token_payload, settings) + .await + .change_context(core::errors::ApiErrorResponse::InternalServerError)?; + Ok(Secret::new(token)) + } +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 8f0b9bad3e8..0d6636e567d 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -165,6 +165,14 @@ pub enum Flow { RefundsList, // Retrieve forex flow. RetrieveForexFlow, + /// Toggles recon service for a merchant. + ReconMerchantUpdate, + /// Recon token request flow. + ReconTokenRequest, + /// Initial request for recon service. + ReconServiceRequest, + /// Recon token verification flow + ReconVerifyToken, /// Routing create flow, RoutingCreateConfig, /// Routing link config
2024-01-12T15:28:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds recon APIs for activating recon as a feature on HyperSwitch dashboard and generating tokens for Recon dashboard. Issue - #3359 ### 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? Tested below endpoints for Recon service using the attached postman collection. Postman collection - https://galactic-capsule-229427.postman.co/workspace/My-Workspace~2b563e0d-bad3-420f-8c0b-0fd5b278a4fe/collection/9906252-4ef01bc4-53d4-40c0-a3e7-c84c8e32f105?action=share&creator=9906252 **Endpoints** 1. `/recon/update_merchant` - admin API call for updating any recon related field for a given merchant. 2. `/recon/token` - request a token for an user which is used for logging into Recon's dashboard. 3. `/recon/request` - let's user send a mail to HS team for enabling recon for their merchant's account. 4. `/recon/verify_token` - validate a generated token. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
58cc8d6109ce49d385b06c762ab3f6670f5094eb
juspay/hyperswitch
juspay__hyperswitch-3379
Bug: [FEATURE] Pass Customer name to connectors ### Feature Description I need customer_name to be passed to stripe. This is required for evaluating the risk associated with a payment. ### Possible Implementation Pass the `name` field ( `customer.name` ) when creating a customer at the connector. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 01ae751f748..596ea1145ec 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -147,7 +147,7 @@ pub struct StaxCustomerRequest { #[serde(skip_serializing_if = "Option::is_none")] email: Option<Email>, #[serde(skip_serializing_if = "Option::is_none")] - firstname: Option<String>, + firstname: Option<Secret<String>>, } impl TryFrom<&types::ConnectorCustomerRouterData> for StaxCustomerRequest { diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 89e18692414..1dbb310868a 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2018,7 +2018,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { description: item.request.description.to_owned(), email: item.request.email.to_owned(), phone: item.request.phone.to_owned(), - name: item.request.name.to_owned().map(Secret::new), + name: item.request.name.to_owned(), source: item.request.preprocessing_id.to_owned(), }) } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 15c79f4b9d9..c6de222f7d8 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -376,7 +376,7 @@ impl<F> TryFrom<&types::RouterData<F, types::PaymentsAuthorizeData, types::Payme payment_method_data: data.request.payment_method_data.clone(), description: None, phone: None, - name: None, + name: data.request.customer_name.clone(), preprocessing_id: data.preprocessing_id.clone(), }) } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5ab6bffc8e6..c7b1ecc2669 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -34,7 +34,7 @@ pub async fn construct_payment_router_data<'a, F, T>( connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, - customer: &Option<domain::Customer>, + customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where @@ -89,6 +89,7 @@ where connector_name: connector_id.to_string(), payment_data: payment_data.clone(), state, + customer_data: customer, }; let customer_id = customer.to_owned().map(|customer| customer.customer_id); @@ -968,6 +969,7 @@ where connector_name: String, payment_data: PaymentData<F>, state: &'a AppState, + customer_data: &'a Option<domain::Customer>, } impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; @@ -1048,6 +1050,17 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .as_ref() .map(|surcharge_details| surcharge_details.final_amount) .unwrap_or(payment_data.amount.into()); + + let customer_name = additional_data + .customer_data + .as_ref() + .and_then(|customer_data| { + customer_data + .name + .as_ref() + .map(|customer| customer.clone().into_inner()) + }); + Ok(Self { payment_method_data: payment_method_data.get_required_value("payment_method_data")?, setup_future_usage: payment_data.payment_intent.setup_future_usage, @@ -1062,6 +1075,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz currency: payment_data.currency, browser_info, email: payment_data.email, + customer_name, payment_experience: payment_data.payment_attempt.payment_experience, order_details, order_category, @@ -1354,6 +1368,17 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; + + let customer_name = additional_data + .customer_data + .as_ref() + .and_then(|customer_data| { + customer_data + .name + .as_ref() + .map(|customer| customer.clone().into_inner()) + }); + Ok(Self { currency: payment_data.currency, confirm: true, @@ -1368,6 +1393,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ setup_mandate_details: payment_data.setup_mandate, router_return_url, email: payment_data.email, + customer_name, return_url: payment_data.payment_intent.return_url, browser_info, payment_method_type: attempt.payment_method_type, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index e236113e676..0809ca17820 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -392,6 +392,7 @@ pub struct PaymentsAuthorizeData { /// ``` pub amount: i64, pub email: Option<Email>, + pub customer_name: Option<Secret<String>>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, @@ -461,7 +462,7 @@ pub struct ConnectorCustomerData { pub description: Option<String>, pub email: Option<Email>, pub phone: Option<Secret<String>>, - pub name: Option<String>, + pub name: Option<Secret<String>>, pub preprocessing_id: Option<String>, pub payment_method_data: payments::PaymentMethodData, } @@ -586,6 +587,7 @@ pub struct SetupMandateRequestData { pub router_return_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub email: Option<Email>, + pub customer_name: Option<Secret<String>>, pub return_url: Option<String>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub request_incremental_authorization: bool, @@ -1342,19 +1344,6 @@ impl From<&&mut PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData { } } -impl From<&&mut PaymentsAuthorizeRouterData> for ConnectorCustomerData { - fn from(data: &&mut PaymentsAuthorizeRouterData) -> Self { - Self { - email: data.request.email.to_owned(), - preprocessing_id: data.preprocessing_id.to_owned(), - payment_method_data: data.request.payment_method_data.to_owned(), - description: None, - phone: None, - name: None, - } - } -} - impl<F> From<&RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>> for PaymentMethodTokenizationData { @@ -1411,6 +1400,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData { setup_mandate_details: data.request.setup_mandate_details.clone(), router_return_url: data.request.router_return_url.clone(), email: data.request.email.clone(), + customer_name: data.request.customer_name.clone(), amount: 0, statement_descriptor: None, capture_method: None, diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index c5fcce8b185..fbd94230584 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -24,6 +24,7 @@ impl VerifyConnectorData { types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(self.card_details.clone()), email: None, + customer_name: None, amount: 1000, confirm: true, currency: storage_enums::Currency::USD, diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 35c9cbd952d..c820b7acd6e 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -59,6 +59,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { order_details: None, order_category: None, email: None, + customer_name: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 49075080506..430ae0bac14 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -147,6 +147,7 @@ impl AdyenTest { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index 8bac7c13c85..892d5b1f208 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -81,6 +81,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 68c4eb94bf3..9d082445719 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -57,6 +57,7 @@ impl CashtocodeTest { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type, session_token: None, diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 73ee93178c0..9a476df7fe6 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -83,6 +83,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index 5df8d80461f..5e1b3f5ab47 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -81,6 +81,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index b140a7c0517..69edec2af2c 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -82,6 +82,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index db82cd7e032..ed3cdbe31b5 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -900,6 +900,7 @@ impl Default for PaymentAuthorizeType { order_details: None, order_category: None, email: None, + customer_name: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 4f7a94780a5..8b865789003 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -92,6 +92,7 @@ impl WorldlineTest { order_details: None, order_category: None, email: None, + customer_name: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None,
2024-01-18T08:58:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> This PR adds the support for sending `customer_name` to the connectors when creating the customer at the connectors end. ### 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). --> Passing customer name to the connector might be required for metadata scanning to evaluate the payment score and risk associated with a payment. ## 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 payment for stripe connector with customer id, email and customer name. ```bash curl --location 'https://sandbox.hyperswitch.io/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_16svHskpygTeiHAoy6RsRf3YxKlSV67FhT5P49UvfA73P1sTG1Tm6VG58a2B79Il' \ --data-raw '{ "amount": 696969, "currency": "USD", "confirm": true, "name": "John Cena", "capture_method": "automatic", "phone": "999999999", "phone_country_code": "+65", "customer_id": "new_stripe_customer_7", "email": "example@juspay.in", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "key1":"hello" } }' ``` - Check the customer name at stripe dashboard. <img width="507" alt="image" src="https://github.com/juspay/hyperswitch/assets/48803246/9df093e0-a66b-41ce-82c0-1b5567d7b4e2"> ## 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
6c46e9c19b304bb11f304e60c46e8abf67accf6d
juspay/hyperswitch
juspay__hyperswitch-3347
Bug: Refactor `s3` to extend other storage logics and provide a runtime flag for the same Provide a runtime flag to handle file storage operations
diff --git a/Cargo.lock b/Cargo.lock index f920b1ea9c5..b86facad816 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2481,6 +2481,7 @@ dependencies = [ "async-trait", "aws-config", "aws-sdk-kms", + "aws-sdk-s3", "aws-sdk-sesv2", "aws-sdk-sts", "aws-smithy-client", @@ -2726,9 +2727,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -2736,9 +2737,9 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" @@ -2764,9 +2765,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-lite" @@ -2785,9 +2786,9 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", @@ -2796,15 +2797,15 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-timer" @@ -2814,9 +2815,9 @@ checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" [[package]] name = "futures-util" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -5155,8 +5156,6 @@ dependencies = [ "async-bb8-diesel", "async-trait", "awc", - "aws-config", - "aws-sdk-s3", "base64 0.21.5", "bb8", "bigdecimal", diff --git a/config/config.example.toml b/config/config.example.toml index 0ad50736e9e..27d1f8b18c5 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -535,3 +535,11 @@ refund_analytics_topic = "topic" # Kafka topic to be used for Refund events api_logs_topic = "topic" # Kafka topic to be used for incoming api events connector_logs_topic = "topic" # Kafka topic to be used for connector api events outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events + +# File storage configuration +[file_storage] +file_storage_backend = "aws_s3" # File storage backend to be used + +[file_storage.aws_s3] +region = "us-east-1" # The AWS region used by the AWS S3 for file storage +bucket_name = "bucket1" # The AWS S3 bucket name for file storage diff --git a/config/development.toml b/config/development.toml index b23f68680e6..5fbe9607cd3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -544,3 +544,6 @@ client_id = "" client_secret = "" partner_id = "" enabled = true + +[file_storage] +file_storage_backend = "file_system" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8af1528e177..8dd01a3d1ce 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -399,3 +399,6 @@ enabled = true [events] source = "logs" + +[file_storage] +file_storage_backend = "file_system" diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 6552b57b0e5..bf836af71a7 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [features] kms = ["dep:aws-config", "dep:aws-sdk-kms"] email = ["dep:aws-config"] +aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = [ "dep:vaultrs" ] [dependencies] @@ -18,6 +19,7 @@ aws-config = { version = "0.55.3", optional = true } aws-sdk-kms = { version = "0.28.0", optional = true } aws-sdk-sesv2 = "0.28.0" aws-sdk-sts = "0.28.0" +aws-sdk-s3 = { version = "0.28.0", optional = true } aws-smithy-client = "0.55.3" base64 = "0.21.2" dyn-clone = "1.0.11" diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs new file mode 100644 index 00000000000..fb419b6ec64 --- /dev/null +++ b/crates/external_services/src/file_storage.rs @@ -0,0 +1,96 @@ +//! +//! Module for managing file storage operations with support for multiple storage schemes. +//! + +use std::fmt::{Display, Formatter}; + +use common_utils::errors::CustomResult; + +/// Includes functionality for AWS S3 storage operations. +#[cfg(feature = "aws_s3")] +mod aws_s3; + +mod file_system; + +/// Enum representing different file storage configurations, allowing for multiple storage schemes. +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(tag = "file_storage_backend")] +#[serde(rename_all = "snake_case")] +pub enum FileStorageConfig { + /// AWS S3 storage configuration. + #[cfg(feature = "aws_s3")] + AwsS3 { + /// Configuration for AWS S3 file storage. + aws_s3: aws_s3::AwsFileStorageConfig, + }, + /// Local file system storage configuration. + #[default] + FileSystem, +} + +impl FileStorageConfig { + /// Validates the file storage configuration. + pub fn validate(&self) -> Result<(), InvalidFileStorageConfig> { + match self { + #[cfg(feature = "aws_s3")] + Self::AwsS3 { aws_s3 } => aws_s3.validate(), + Self::FileSystem => Ok(()), + } + } + + /// Retrieves the appropriate file storage client based on the file storage configuration. + pub async fn get_file_storage_client(&self) -> Box<dyn FileStorageInterface> { + match self { + #[cfg(feature = "aws_s3")] + Self::AwsS3 { aws_s3 } => Box::new(aws_s3::AwsFileStorageClient::new(aws_s3).await), + Self::FileSystem => Box::new(file_system::FileSystem), + } + } +} + +/// Trait for file storage operations +#[async_trait::async_trait] +pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send { + /// Uploads a file to the selected storage scheme. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError>; + + /// Deletes a file from the selected storage scheme. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError>; + + /// Retrieves a file from the selected storage scheme. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError>; +} + +dyn_clone::clone_trait_object!(FileStorageInterface); + +/// Error thrown when the file storage config is invalid +#[derive(Debug, Clone)] +pub struct InvalidFileStorageConfig(&'static str); + +impl std::error::Error for InvalidFileStorageConfig {} + +impl Display for InvalidFileStorageConfig { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "file_storage: {}", self.0) + } +} + +/// Represents errors that can occur during file storage operations. +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum FileStorageError { + /// Indicates that the file upload operation failed. + #[error("Failed to upload file")] + UploadFailed, + + /// Indicates that the file retrieval operation failed. + #[error("Failed to retrieve file")] + RetrieveFailed, + + /// Indicates that the file deletion operation failed. + #[error("Failed to delete file")] + DeleteFailed, +} diff --git a/crates/external_services/src/file_storage/aws_s3.rs b/crates/external_services/src/file_storage/aws_s3.rs new file mode 100644 index 00000000000..86d1c0f0efa --- /dev/null +++ b/crates/external_services/src/file_storage/aws_s3.rs @@ -0,0 +1,158 @@ +use aws_config::meta::region::RegionProviderChain; +use aws_sdk_s3::{ + operation::{ + delete_object::DeleteObjectError, get_object::GetObjectError, put_object::PutObjectError, + }, + Client, +}; +use aws_sdk_sts::config::Region; +use common_utils::{errors::CustomResult, ext_traits::ConfigExt}; +use error_stack::ResultExt; + +use super::InvalidFileStorageConfig; +use crate::file_storage::{FileStorageError, FileStorageInterface}; + +/// Configuration for AWS S3 file storage. +#[derive(Debug, serde::Deserialize, Clone, Default)] +#[serde(default)] +pub struct AwsFileStorageConfig { + /// The AWS region to send file uploads + region: String, + /// The AWS s3 bucket to send file uploads + bucket_name: String, +} + +impl AwsFileStorageConfig { + /// Validates the AWS S3 file storage configuration. + pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> { + use common_utils::fp_utils::when; + + when(self.region.is_default_or_empty(), || { + Err(InvalidFileStorageConfig("aws s3 region must not be empty")) + })?; + + when(self.bucket_name.is_default_or_empty(), || { + Err(InvalidFileStorageConfig( + "aws s3 bucket name must not be empty", + )) + }) + } +} + +/// AWS S3 file storage client. +#[derive(Debug, Clone)] +pub(super) struct AwsFileStorageClient { + /// AWS S3 client + inner_client: Client, + /// The name of the AWS S3 bucket. + bucket_name: String, +} + +impl AwsFileStorageClient { + /// Creates a new AWS S3 file storage client. + pub(super) async fn new(config: &AwsFileStorageConfig) -> Self { + let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone())); + let sdk_config = aws_config::from_env().region(region_provider).load().await; + Self { + inner_client: Client::new(&sdk_config), + bucket_name: config.bucket_name.clone(), + } + } + + /// Uploads a file to AWS S3. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), AwsS3StorageError> { + self.inner_client + .put_object() + .bucket(&self.bucket_name) + .key(file_key) + .body(file.into()) + .send() + .await + .map_err(AwsS3StorageError::UploadFailure)?; + Ok(()) + } + + /// Deletes a file from AWS S3. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), AwsS3StorageError> { + self.inner_client + .delete_object() + .bucket(&self.bucket_name) + .key(file_key) + .send() + .await + .map_err(AwsS3StorageError::DeleteFailure)?; + Ok(()) + } + + /// Retrieves a file from AWS S3. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, AwsS3StorageError> { + Ok(self + .inner_client + .get_object() + .bucket(&self.bucket_name) + .key(file_key) + .send() + .await + .map_err(AwsS3StorageError::RetrieveFailure)? + .body + .collect() + .await + .map_err(AwsS3StorageError::UnknownError)? + .to_vec()) + } +} + +#[async_trait::async_trait] +impl FileStorageInterface for AwsFileStorageClient { + /// Uploads a file to AWS S3. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError> { + self.upload_file(file_key, file) + .await + .change_context(FileStorageError::UploadFailed)?; + Ok(()) + } + + /// Deletes a file from AWS S3. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> { + self.delete_file(file_key) + .await + .change_context(FileStorageError::DeleteFailed)?; + Ok(()) + } + + /// Retrieves a file from AWS S3. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> { + Ok(self + .retrieve_file(file_key) + .await + .change_context(FileStorageError::RetrieveFailed)?) + } +} + +/// Enum representing errors that can occur during AWS S3 file storage operations. +#[derive(Debug, thiserror::Error)] +enum AwsS3StorageError { + /// Error indicating that file upload to S3 failed. + #[error("File upload to S3 failed: {0:?}")] + UploadFailure(aws_smithy_client::SdkError<PutObjectError>), + + /// Error indicating that file retrieval from S3 failed. + #[error("File retrieve from S3 failed: {0:?}")] + RetrieveFailure(aws_smithy_client::SdkError<GetObjectError>), + + /// Error indicating that file deletion from S3 failed. + #[error("File delete from S3 failed: {0:?}")] + DeleteFailure(aws_smithy_client::SdkError<DeleteObjectError>), + + /// Unknown error occurred. + #[error("Unknown error occurred: {0:?}")] + UnknownError(aws_sdk_s3::primitives::ByteStreamError), +} diff --git a/crates/external_services/src/file_storage/file_system.rs b/crates/external_services/src/file_storage/file_system.rs new file mode 100644 index 00000000000..15ca84deeb8 --- /dev/null +++ b/crates/external_services/src/file_storage/file_system.rs @@ -0,0 +1,144 @@ +//! +//! Module for local file system storage operations +//! + +use std::{ + fs::{remove_file, File}, + io::{Read, Write}, + path::PathBuf, +}; + +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; + +use crate::file_storage::{FileStorageError, FileStorageInterface}; + +/// Constructs the file path for a given file key within the file system. +/// The file path is generated based on the workspace path and the provided file key. +fn get_file_path(file_key: impl AsRef<str>) -> PathBuf { + let mut file_path = PathBuf::new(); + #[cfg(feature = "logs")] + file_path.push(router_env::env::workspace_path()); + #[cfg(not(feature = "logs"))] + file_path.push(std::env::current_dir().unwrap_or(".".into())); + + file_path.push("files"); + file_path.push(file_key.as_ref()); + file_path +} + +/// Represents a file system for storing and managing files locally. +#[derive(Debug, Clone)] +pub(super) struct FileSystem; + +impl FileSystem { + /// Saves the provided file data to the file system under the specified file key. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileSystemStorageError> { + let file_path = get_file_path(file_key); + + // Ignore the file name and create directories in the `file_path` if not exists + std::fs::create_dir_all( + file_path + .parent() + .ok_or(FileSystemStorageError::CreateDirFailed) + .into_report() + .attach_printable("Failed to obtain parent directory")?, + ) + .into_report() + .change_context(FileSystemStorageError::CreateDirFailed)?; + + let mut file_handler = File::create(file_path) + .into_report() + .change_context(FileSystemStorageError::CreateFailure)?; + file_handler + .write_all(&file) + .into_report() + .change_context(FileSystemStorageError::WriteFailure)?; + Ok(()) + } + + /// Deletes the file associated with the specified file key from the file system. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileSystemStorageError> { + let file_path = get_file_path(file_key); + remove_file(file_path) + .into_report() + .change_context(FileSystemStorageError::DeleteFailure)?; + Ok(()) + } + + /// Retrieves the file content associated with the specified file key from the file system. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileSystemStorageError> { + let mut received_data: Vec<u8> = Vec::new(); + let file_path = get_file_path(file_key); + let mut file = File::open(file_path) + .into_report() + .change_context(FileSystemStorageError::FileOpenFailure)?; + file.read_to_end(&mut received_data) + .into_report() + .change_context(FileSystemStorageError::ReadFailure)?; + Ok(received_data) + } +} + +#[async_trait::async_trait] +impl FileStorageInterface for FileSystem { + /// Saves the provided file data to the file system under the specified file key. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError> { + self.upload_file(file_key, file) + .await + .change_context(FileStorageError::UploadFailed)?; + Ok(()) + } + + /// Deletes the file associated with the specified file key from the file system. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> { + self.delete_file(file_key) + .await + .change_context(FileStorageError::DeleteFailed)?; + Ok(()) + } + + /// Retrieves the file content associated with the specified file key from the file system. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> { + Ok(self + .retrieve_file(file_key) + .await + .change_context(FileStorageError::RetrieveFailed)?) + } +} + +/// Represents an error that can occur during local file system storage operations. +#[derive(Debug, thiserror::Error)] +enum FileSystemStorageError { + /// Error indicating opening a file failed + #[error("Failed while opening the file")] + FileOpenFailure, + + /// Error indicating file creation failed. + #[error("Failed to create file")] + CreateFailure, + + /// Error indicating reading a file failed. + #[error("Failed while reading the file")] + ReadFailure, + + /// Error indicating writing to a file failed. + #[error("Failed while writing into file")] + WriteFailure, + + /// Error indicating file deletion failed. + #[error("Failed while deleting the file")] + DeleteFailure, + + /// Error indicating directory creation failed + #[error("Failed while creating a directory")] + CreateDirFailed, +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 9bf4916eec3..bba65873e91 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -9,6 +9,7 @@ pub mod email; #[cfg(feature = "kms")] pub mod kms; +pub mod file_storage; #[cfg(feature = "hashicorp-vault")] pub mod hashicorp_vault; diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e575daf7e7a..3d129edfe3f 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,10 +10,10 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] -aws_s3 = ["dep:aws-sdk-s3", "dep:aws-config"] -kms = ["external_services/kms", "dep:aws-config"] +aws_s3 = ["external_services/aws_s3"] +kms = ["external_services/kms"] hashicorp-vault = ["external_services/hashicorp-vault"] -email = ["external_services/email", "dep:aws-config", "olap"] +email = ["external_services/email", "olap"] frm = [] stripe = ["dep:serde_qs"] release = ["kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] @@ -42,8 +42,6 @@ actix-web = "4.3.1" async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } argon2 = { version = "0.5.0", features = ["std"] } async-trait = "0.1.68" -aws-config = { version = "0.55.3", optional = true } -aws-sdk-s3 = { version = "0.28.0", optional = true } base64 = "0.21.2" bb8 = "0.8" bigdecimal = "0.3.1" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3c1d9f7d397..146a1ace28e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -11,6 +11,7 @@ use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; #[cfg(feature = "email")] use external_services::email::EmailSettings; +use external_services::file_storage::FileStorageConfig; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; #[cfg(feature = "kms")] @@ -90,10 +91,9 @@ pub struct Settings { pub api_keys: ApiKeys, #[cfg(feature = "kms")] pub kms: kms::KmsConfig, + pub file_storage: FileStorageConfig, #[cfg(feature = "hashicorp-vault")] pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, - #[cfg(feature = "aws_s3")] - pub file_upload_config: FileUploadConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] @@ -721,16 +721,6 @@ pub struct ApiKeys { pub expiry_reminder_days: Vec<u8>, } -#[cfg(feature = "aws_s3")] -#[derive(Debug, Deserialize, Clone, Default)] -#[serde(default)] -pub struct FileUploadConfig { - /// The AWS region to send file uploads - pub region: String, - /// The AWS s3 bucket to send file uploads - pub bucket_name: String, -} - #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { #[serde(deserialize_with = "deser_to_get_connectors")] @@ -853,8 +843,11 @@ impl Settings { self.kms .validate() .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; - #[cfg(feature = "aws_s3")] - self.file_upload_config.validate()?; + + self.file_storage + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + self.lock_settings.validate()?; self.events.validate()?; Ok(()) diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 0b286ece843..910ae754347 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -127,25 +127,6 @@ impl super::settings::DrainerSettings { } } -#[cfg(feature = "aws_s3")] -impl super::settings::FileUploadConfig { - pub fn validate(&self) -> Result<(), ApplicationError> { - use common_utils::fp_utils::when; - - when(self.region.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "s3 region must not be empty".into(), - )) - })?; - - when(self.bucket_name.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "s3 bucket name must not be empty".into(), - )) - }) - } -} - impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index f3e56489806..d3f490a0a6c 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -1,9 +1,4 @@ pub mod helpers; -#[cfg(feature = "aws_s3")] -pub mod s3_utils; - -#[cfg(not(feature = "aws_s3"))] -pub mod fs_utils; use api_models::files; use error_stack::{IntoReport, ResultExt}; @@ -29,10 +24,7 @@ pub async fn files_create_core( ) .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); - #[cfg(feature = "aws_s3")] let file_key = format!("{}/{}", merchant_account.merchant_id, file_id); - #[cfg(not(feature = "aws_s3"))] - let file_key = format!("{}_{}", merchant_account.merchant_id, file_id); let file_new = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), merchant_id: merchant_account.merchant_id.clone(), diff --git a/crates/router/src/core/files/fs_utils.rs b/crates/router/src/core/files/fs_utils.rs deleted file mode 100644 index 795f2fad759..00000000000 --- a/crates/router/src/core/files/fs_utils.rs +++ /dev/null @@ -1,57 +0,0 @@ -use std::{ - fs::{remove_file, File}, - io::{Read, Write}, - path::PathBuf, -}; - -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; - -use crate::{core::errors, env}; - -pub fn get_file_path(file_key: String) -> PathBuf { - let mut file_path = PathBuf::new(); - file_path.push(env::workspace_path()); - file_path.push("files"); - file_path.push(file_key); - file_path -} - -pub fn save_file_to_fs( - file_key: String, - file_data: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let file_path = get_file_path(file_key); - let mut file = File::create(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to create file")?; - file.write_all(&file_data) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while writing into file")?; - Ok(()) -} - -pub fn delete_file_from_fs(file_key: String) -> CustomResult<(), errors::ApiErrorResponse> { - let file_path = get_file_path(file_key); - remove_file(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while deleting the file")?; - Ok(()) -} - -pub fn retrieve_file_from_fs(file_key: String) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - let mut received_data: Vec<u8> = Vec::new(); - let file_path = get_file_path(file_key); - let mut file = File::open(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while opening the file")?; - file.read_to_end(&mut received_data) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while reading the file")?; - Ok(received_data) -} diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 9205d42aeee..0a509b238af 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -6,7 +6,7 @@ use futures::TryStreamExt; use crate::{ core::{ errors::{self, StorageErrorExt}, - files, payments, utils, + payments, utils, }, routes::AppState, services, @@ -30,37 +30,6 @@ pub async fn get_file_purpose(field: &mut Field) -> Option<api::FilePurpose> { } } -pub async fn upload_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, - file: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::upload_file_to_s3(state, file_key, file).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::save_file_to_fs(file_key, file); -} - -pub async fn delete_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, -) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::delete_file_from_s3(state, file_key).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::delete_file_from_fs(file_key); -} - -pub async fn retrieve_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, -) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::retrieve_file_from_s3(state, file_key).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::retrieve_file_from_fs(file_key); -} - pub async fn validate_file_upload( state: &AppState, merchant_account: domain::MerchantAccount, @@ -132,14 +101,11 @@ pub async fn delete_file_using_file_id( .attach_printable("File not available")?, }; match provider { - diesel_models::enums::FileUploadProvider::Router => { - delete_file( - #[cfg(feature = "aws_s3")] - state, - provider_file_id, - ) + diesel_models::enums::FileUploadProvider::Router => state + .file_storage_client + .delete_file(&provider_file_id) .await - } + .change_context(errors::ApiErrorResponse::InternalServerError), _ => Err(errors::ApiErrorResponse::FileProviderNotSupported { message: "Not Supported because provider is not Router".to_string(), } @@ -234,12 +200,11 @@ pub async fn retrieve_file_and_provider_file_id_from_file_id( match provider { diesel_models::enums::FileUploadProvider::Router => Ok(( Some( - retrieve_file( - #[cfg(feature = "aws_s3")] - state, - provider_file_id.clone(), - ) - .await?, + state + .file_storage_client + .retrieve_file(&provider_file_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?, ), Some(provider_file_id), )), @@ -364,13 +329,11 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( payment_attempt.merchant_connector_id, )) } else { - upload_file( - #[cfg(feature = "aws_s3")] - state, - file_key.clone(), - create_file_request.file.clone(), - ) - .await?; + state + .file_storage_client + .upload_file(&file_key, create_file_request.file.clone()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(( file_key, api_models::enums::FileUploadProvider::Router, diff --git a/crates/router/src/core/files/s3_utils.rs b/crates/router/src/core/files/s3_utils.rs deleted file mode 100644 index 228c23528cd..00000000000 --- a/crates/router/src/core/files/s3_utils.rs +++ /dev/null @@ -1,87 +0,0 @@ -use aws_config::{self, meta::region::RegionProviderChain}; -use aws_sdk_s3::{config::Region, Client}; -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; -use futures::TryStreamExt; - -use crate::{core::errors, routes}; - -async fn get_aws_client(state: &routes::AppState) -> Client { - let region_provider = - RegionProviderChain::first_try(Region::new(state.conf.file_upload_config.region.clone())); - let sdk_config = aws_config::from_env().region(region_provider).load().await; - Client::new(&sdk_config) -} - -pub async fn upload_file_to_s3( - state: &routes::AppState, - file_key: String, - file: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Upload file to S3 - let upload_res = client - .put_object() - .bucket(bucket_name) - .key(file_key.clone()) - .body(file.into()) - .send() - .await; - upload_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File upload to S3 failed")?; - Ok(()) -} - -pub async fn delete_file_from_s3( - state: &routes::AppState, - file_key: String, -) -> CustomResult<(), errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Delete file from S3 - let delete_res = client - .delete_object() - .bucket(bucket_name) - .key(file_key) - .send() - .await; - delete_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File delete from S3 failed")?; - Ok(()) -} - -pub async fn retrieve_file_from_s3( - state: &routes::AppState, - file_key: String, -) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Get file data from S3 - let get_res = client - .get_object() - .bucket(bucket_name) - .key(file_key) - .send() - .await; - let mut object = get_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File retrieve from S3 failed")?; - let mut received_data: Vec<u8> = Vec::new(); - while let Some(bytes) = object - .body - .try_next() - .await - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid file data received from S3")? - { - received_data.extend_from_slice(&bytes); // Collect the bytes in the Vec - } - Ok(received_data) -} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f490cee8dab..2b26a5e7586 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -5,6 +5,7 @@ use actix_web::{web, Scope}; use analytics::AnalyticsConfig; #[cfg(feature = "email")] use external_services::email::{ses::AwsSes, EmailService}; +use external_services::file_storage::FileStorageInterface; #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] use external_services::hashicorp_vault::decrypt::VaultFetch; #[cfg(feature = "kms")] @@ -68,6 +69,7 @@ pub struct AppState { #[cfg(feature = "olap")] pub pool: crate::analytics::AnalyticsProvider, pub request_id: Option<RequestId>, + pub file_storage_client: Box<dyn FileStorageInterface>, } impl scheduler::SchedulerAppState for AppState { @@ -266,6 +268,8 @@ impl AppState { #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await); + let file_storage_client = conf.file_storage.get_file_storage_client().await; + Self { flow_name: String::from("default"), store, @@ -279,6 +283,7 @@ impl AppState { #[cfg(feature = "olap")] pool, request_id: None, + file_storage_client, } }) .await diff --git a/docker-compose.yml b/docker-compose.yml index 3839269a522..e55008f1e34 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -54,6 +54,7 @@ services: - router_net volumes: - ./config:/local/config + - ./files:/local/bin/files labels: logs: "promtail" healthcheck:
2024-01-14T14:27:35Z
## 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 includes refactoring for: * Enabling easy extension of other file storage schemes. * Providing a runtime flag for the file storage feature. * Restrict the file storage objects(structs, methods) visibility wherever possible. ### 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 #3338, Closes #3347 ## 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 dispute and get the `dispute_id` ### File System 1. File uploading ``` curl --location --request POST 'localhost:8080/files' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' \ --header 'Content-Type: multipart/form-data; boundary=6467930559a8e09e-babf866111649afb-06f42165ce9a45a7-bc825186544537e1' \ --header 'Accept-Encoding: gzip' \ --form 'purpose="dispute_evidence"' \ --form 'file=@"/Users/sai.harsha/Desktop/dummy.pdf"' \ --form 'dispute_id="dp_Hv9m2MJGRjptYmEYPqFa"' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/ddec5aff-a0e3-4d09-9d0d-32f698e0c3cc) 2. File retrieve ``` curl --location --request GET 'localhost:8080/files/file_qXP0X6uAgLwSvswj8T41' \ --header 'Accept: application/json' \ --header 'api-key: dev_H3Uf7cssLge9XnWZZfV2M5xwqroMHt46cXh0EwXJQHTdYuBTVC3KVnA5Fo45hagw' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/efe193e3-b5d7-4f30-8546-c499a6c36483) 3. File delete ``` curl --location --request DELETE 'localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/a724d0b7-1c80-4c62-9b2e-2fd20205c681) ### Aws S3 1. File uploading ![image](https://github.com/juspay/hyperswitch/assets/70657455/e4077964-e117-4f50-8e9b-25bdcb794a9a) 2. File retrieve ![image](https://github.com/juspay/hyperswitch/assets/70657455/b7d3e799-0fde-48a2-aac0-513faa49523e) 3. File delete ![image (1)](https://github.com/juspay/hyperswitch/assets/70657455/e398faeb-0697-483c-8a41-dd5bd47d5e18) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3fbffdc242dafe7983c542573b7c6362f99331e6
juspay/hyperswitch
juspay__hyperswitch-3361
Bug: [REFACTOR] Add config to enable and disable locker ### Feature Description Add config to disable or enable locker. If the config is set as false then we don't store the card_details in locker else we store the details in the locker. ### Possible Implementation While a payment gets created, make a decision based on the config to either save or not save in the locker. When the locker has been disabled, no cards are saved hence no payment_token is generated for that payment and while listing the mandates we shouldn't make a call to the locker, we should be able to decrypt the value in `payment_method_data` field and give back the details. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index d4e11964192..cf25ef195a2 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -131,6 +131,7 @@ host_rs = "" # Rust Locker host mock_locker = true # Emulate a locker locally using Postgres basilisk_host = "" # Basilisk host locker_signing_key_id = "1" # Key_id to sign basilisk hs locker +locker_enabled = true # Boolean to enable or disable saving cards in locker [delayed_session_response] connectors_with_delayed_session_response = "trustpay,payme" # List of connectors which has delayed session response diff --git a/config/development.toml b/config/development.toml index 91269005a0f..b23f68680e6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -69,6 +69,8 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true + [forex_api] call_delay = 21600 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 450fe106a31..8af1528e177 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -56,6 +56,7 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true [jwekey] vault_encryption_key = "" diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 5c0810dc21b..b29f4e0d0c3 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -36,6 +36,8 @@ pub struct MandateResponse { pub payment_method_id: String, /// The payment method pub payment_method: String, + /// The payment method type + pub payment_method_type: Option<String>, /// The card details for mandate pub card: Option<MandateCardDetails>, /// Details about the customer’s acceptance @@ -66,6 +68,15 @@ pub struct MandateCardDetails { #[schema(value_type = Option<String>)] /// A unique identifier alias to identify a particular card pub card_fingerprint: Option<Secret<String>>, + /// The first 6 digits of card + pub card_isin: Option<String>, + /// The bank that issued the card + pub card_issuer: Option<String>, + /// The network that facilitates payment card transactions + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + /// The type of the payment card + pub card_type: Option<String>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 3467777da74..984e6dbffff 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -109,6 +109,19 @@ pub struct CardDetail { /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, + + /// Card Issuing Country + pub card_issuing_country: Option<String>, + + /// Card's Network + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + /// Issuer Bank for Card + pub card_issuer: Option<String>, + + /// Card Type + pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -177,6 +190,12 @@ pub struct CardDetailsPaymentMethod { pub expiry_year: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_network: Option<api_enums::CardNetwork>, + pub card_type: Option<String>, + #[serde(default = "saved_in_locker_default")] + pub saved_to_locker: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] @@ -227,6 +246,18 @@ pub struct CardDetailFromLocker { #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, + + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_type: Option<String>, + pub saved_to_locker: bool, +} + +fn saved_in_locker_default() -> bool { + true } impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { @@ -242,6 +273,11 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, } } } @@ -255,6 +291,11 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, } } } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 42839bf3513..e4a470d0da3 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -54,6 +54,8 @@ impl Default for super::settings::Locker { mock_locker: true, basilisk_host: "localhost".into(), locker_signing_key_id: "1".into(), + //true or false + locker_enabled: true, } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3d93c2f188b..bcf26d63ae8 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -490,6 +490,7 @@ pub struct Locker { pub mock_locker: bool, pub basilisk_host: String, pub locker_signing_key_id: String, + pub locker_enabled: bool, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index e3e308a8a01..4bd2555792a 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -101,6 +101,10 @@ pub async fn call_to_locker( card_exp_year: card.card_exp_year, card_holder_name: card.name_on_card, nick_name: card.nick_name.map(masking::Secret::new), + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, }; let pm_create = api::PaymentMethodCreate { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index aabd846660c..b6837d14f82 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -33,6 +33,7 @@ use crate::{ pub async fn get_mandate( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateResponse> { let mandate = state @@ -42,7 +43,7 @@ pub async fn get_mandate( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( - mandates::MandateResponse::from_db_mandate(&state, mandate).await?, + mandates::MandateResponse::from_db_mandate(&state, key_store, mandate).await?, )) } @@ -202,6 +203,7 @@ pub async fn update_connector_mandate_id( pub async fn get_customer_mandates( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: customers::CustomerId, ) -> RouterResponse<Vec<mandates::MandateResponse>> { let mandates = state @@ -221,7 +223,10 @@ pub async fn get_customer_mandates( } else { let mut response_vec = Vec::with_capacity(mandates.len()); for mandate in mandates { - response_vec.push(mandates::MandateResponse::from_db_mandate(&state, mandate).await?); + response_vec.push( + mandates::MandateResponse::from_db_mandate(&state, key_store.clone(), mandate) + .await?, + ); } Ok(services::ApplicationResponse::Json(response_vec)) } @@ -383,6 +388,7 @@ where pub async fn retrieve_mandates_list( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, constraints: api_models::mandates::MandateListConstraints, ) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> { let mandates = state @@ -392,11 +398,9 @@ pub async fn retrieve_mandates_list( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve mandates")?; - let mandates_list = future::try_join_all( - mandates - .into_iter() - .map(|mandate| mandates::MandateResponse::from_db_mandate(&state, mandate)), - ) + let mandates_list = future::try_join_all(mandates.into_iter().map(|mandate| { + mandates::MandateResponse::from_db_mandate(&state, key_store.clone(), mandate) + })) .await?; Ok(services::ApplicationResponse::Json(mandates_list)) } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 51f54353635..1a8bbcc8ef7 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -558,6 +558,7 @@ pub async fn add_card_hs( req, &merchant_account.merchant_id, ); + Ok(( payment_method_resp, store_card_payload.duplicate.unwrap_or(false), @@ -2508,11 +2509,19 @@ pub async fn list_customer_payment_method( let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let (card, pmd, hyperswitch_token_data) = match pm.payment_method { - enums::PaymentMethod::Card => ( - Some(get_card_details(&pm, key, state).await?), - None, - PaymentTokenData::permanent_card(pm.payment_method_id.clone()), - ), + enums::PaymentMethod::Card => { + let card_details = get_card_details_with_locker_fallback(&pm, key, state).await?; + + if card_details.is_some() { + ( + card_details, + None, + PaymentTokenData::permanent_card(pm.payment_method_id.clone()), + ) + } else { + continue; + } + } #[cfg(feature = "payouts")] enums::PaymentMethod::BankTransfer => { @@ -2571,6 +2580,7 @@ pub async fn list_customer_payment_method( }; //Need validation for enabled payment method ,querying MCA + let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), customer_id: pm.customer_id, @@ -2700,7 +2710,38 @@ pub async fn list_customer_payment_method( Ok(services::ApplicationResponse::Json(response)) } -async fn get_card_details( +pub async fn get_card_details_with_locker_fallback( + pm: &payment_method::PaymentMethod, + key: &[u8], + state: &routes::AppState, +) -> errors::RouterResult<Option<api::CardDetailFromLocker>> { + let card_decrypted = + decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }); + + Ok(if let Some(mut crd) = card_decrypted { + if crd.saved_to_locker { + crd.scheme = pm.scheme.clone(); + Some(crd) + } else { + None + } + } else { + Some(get_card_details_from_locker(state, pm).await?) + }) +} + +pub async fn get_card_details_without_locker_fallback( pm: &payment_method::PaymentMethod, key: &[u8], state: &routes::AppState, @@ -2971,25 +3012,32 @@ impl TempLockerCardSupport { pub async fn retrieve_payment_method( state: routes::AppState, pm: api::PaymentMethodId, + key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { let db = state.store.as_ref(); let pm = db .find_payment_method(&pm.payment_method_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let key = key_store.key.peek(); let card = if pm.payment_method == enums::PaymentMethod::Card { - let card = get_card_from_locker( - &state, - &pm.customer_id, - &pm.merchant_id, - &pm.payment_method_id, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error getting card from card vault")?; - let card_detail = payment_methods::get_card_detail(&pm, card) + let card_detail = if state.conf.locker.locker_enabled { + let card = get_card_from_locker( + &state, + &pm.customer_id, + &pm.merchant_id, + &pm.payment_method_id, + ) + .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting card details from locker")?; + .attach_printable("Error getting card from card vault")?; + payment_methods::get_card_detail(&pm, card) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting card details from locker")? + } else { + get_card_details_without_locker_fallback(&pm, key, &state).await? + }; Some(card_detail) } else { None diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index da4f03b49c1..304091e42ac 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -352,18 +352,26 @@ pub fn mk_add_card_response_hs( req: api::PaymentMethodCreate, merchant_id: &str, ) -> api::PaymentMethodResponse { - let mut card_number = card.card_number.peek().to_owned(); + let card_number = card.card_number.clone(); + let last4_digits = card_number.clone().get_last4(); + let card_isin = card_number.get_card_isin(); + let card = api::CardDetailFromLocker { scheme: None, - last4_digits: Some(card_number.split_off(card_number.len() - 4)), - issuer_country: None, // [#256] bin mapping - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: None, // [#256] - card_fingerprint: None, // fingerprint not send by basilisk-hs need to have this feature in case we need it in future - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, + last4_digits: Some(last4_digits), + issuer_country: None, + card_number: Some(card.card_number.clone()), + expiry_month: Some(card.card_exp_month.clone()), + expiry_year: Some(card.card_exp_year.clone()), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name.clone(), + nick_name: card.nick_name.clone(), + card_isin: Some(card_isin), + card_issuer: card.card_issuer, + card_network: card.card_network, + card_type: card.card_type, + saved_to_locker: true, }; api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), @@ -399,6 +407,11 @@ pub fn mk_add_card_response( card_fingerprint: Some(response.card_fingerprint), card_holder_name: card.card_holder_name, nick_name: card.nick_name, + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, }; api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), @@ -597,6 +610,8 @@ pub fn get_card_detail( ) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> { let card_number = response.card_number; let mut last4_digits = card_number.peek().to_owned(); + //fetch form card bin + let card_detail = api::CardDetailFromLocker { scheme: pm.scheme.to_owned(), issuer_country: pm.issuer_country.clone(), @@ -608,6 +623,11 @@ pub fn get_card_detail( card_fingerprint: None, card_holder_name: response.name_on_card, nick_name: response.nick_name.map(masking::Secret::new), + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, }; Ok(card_detail) } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 07af15a336d..15c79f4b9d9 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -92,7 +92,9 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics - if resp.request.setup_mandate_details.clone().is_some() { + let is_mandate = resp.request.setup_mandate_details.is_some(); + + if is_mandate { let payment_method_id = Box::pin(tokenization::save_payment_method( state, connector, diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 0c03c8ce123..d6343ed871b 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -208,6 +208,7 @@ impl types::SetupMandateRouterData { .to_setup_mandate_failed_response()?; let payment_method_type = self.request.payment_method_type; + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 92dc1bf5f4b..e3a3ccdc02c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -509,16 +509,23 @@ pub async fn get_token_for_recurring_mandate( }; if let diesel_models::enums::PaymentMethod::Card = payment_method.payment_method { - let _ = - cards::get_lookup_key_from_locker(state, &token, &payment_method, merchant_key_store) - .await?; + if state.conf.locker.locker_enabled { + let _ = cards::get_lookup_key_from_locker( + state, + &token, + &payment_method, + merchant_key_store, + ) + .await?; + } + if let Some(payment_method_from_request) = req.payment_method { let pm: storage_enums::PaymentMethod = payment_method_from_request; if pm != payment_method.payment_method { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "payment method in request does not match previously provided payment \ - method information" + method information" .into() }))? } @@ -971,7 +978,6 @@ pub fn payment_intent_status_fsm( None => storage_enums::IntentStatus::RequiresPaymentMethod, } } - pub async fn add_domain_task_to_pt<Op>( operation: &Op, state: &AppState, @@ -1034,6 +1040,10 @@ pub(crate) async fn get_payment_method_create_request( card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), + card_issuing_country: card.card_issuing_country.clone(), + card_network: card.card_network.clone(), + card_issuer: card.card_issuer.clone(), + card_type: card.card_type.clone(), }; let customer_id = customer.customer_id.clone(); let payment_method_request = api::PaymentMethodCreate { @@ -3343,21 +3353,23 @@ pub async fn get_additional_payment_data( }, )) }); - card_info.unwrap_or(api_models::payments::AdditionalPaymentData::Card(Box::new( - api_models::payments::AdditionalCardInfo { - card_issuer: None, - card_network: None, - bank_code: None, - card_type: None, - card_issuing_country: None, - last4, - card_isin, - card_extended_bin, - card_exp_month: Some(card_data.card_exp_month.clone()), - card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: card_data.card_holder_name.clone(), - }, - ))) + card_info.unwrap_or_else(|| { + api_models::payments::AdditionalPaymentData::Card(Box::new( + api_models::payments::AdditionalCardInfo { + card_issuer: None, + card_network: None, + bank_code: None, + card_type: None, + card_issuing_country: None, + last4, + card_isin, + card_extended_bin, + card_exp_month: Some(card_data.card_exp_month.clone()), + card_exp_year: Some(card_data.card_exp_year.clone()), + card_holder_name: card_data.card_holder_name.clone(), + }, + )) + }) } } api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index f884cb79e7e..15d88c94660 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -14,7 +14,7 @@ use crate::{ services, types::{ self, - api::{self, CardDetailsPaymentMethod, PaymentMethodCreateExt}, + api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, storage::enums as storage_enums, }, @@ -74,12 +74,21 @@ where .await?; let merchant_id = &merchant_account.merchant_id; - let locker_response = save_in_locker( - state, - merchant_account, - payment_method_create_request.to_owned(), - ) - .await?; + let locker_response = if !state.conf.locker.locker_enabled { + skip_saving_card_in_locker( + merchant_account, + payment_method_create_request.to_owned(), + ) + .await? + } else { + save_in_locker( + state, + merchant_account, + payment_method_create_request.to_owned(), + ) + .await? + }; + let is_duplicate = locker_response.1; let pm_card_details = locker_response.0.card.as_ref().map(|card| { @@ -168,6 +177,85 @@ where } } +async fn skip_saving_card_in_locker( + merchant_account: &domain::MerchantAccount, + payment_method_request: api::PaymentMethodCreate, +) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { + let merchant_id = &merchant_account.merchant_id; + let customer_id = payment_method_request + .clone() + .customer_id + .clone() + .get_required_value("customer_id")?; + let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + + let last4_digits = payment_method_request + .card + .clone() + .map(|c| c.card_number.get_last4()); + + let card_isin = payment_method_request + .card + .clone() + .map(|c: api_models::payment_methods::CardDetail| c.card_number.get_card_isin()); + + match payment_method_request.card.clone() { + Some(card) => { + let card_detail = CardDetailFromLocker { + scheme: None, + issuer_country: card.card_issuing_country.clone(), + last4_digits: last4_digits.clone(), + card_number: None, + expiry_month: Some(card.card_exp_month.clone()), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_holder_name: card.card_holder_name.clone(), + card_fingerprint: None, + nick_name: None, + card_isin: card_isin.clone(), + card_issuer: card.card_issuer.clone(), + card_network: card.card_network.clone(), + card_type: card.card_type.clone(), + saved_to_locker: false, + }; + let pm_resp = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: Some(card_detail), + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + metadata: None, + created: Some(common_utils::date_time::now()), + bank_transfer: None, + }; + + Ok((pm_resp, false)) + } + None => { + let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + let payment_method_response = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id: pm_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: None, + metadata: None, + created: Some(common_utils::date_time::now()), + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + bank_transfer: None, + }; + Ok((payment_method_response, false)) + } + } +} + pub async fn save_in_locker( state: &AppState, merchant_account: &domain::MerchantAccount, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 56e3a6faf53..1ab24023bdb 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,6 +1,6 @@ use common_utils::{ errors::CustomResult, - ext_traits::{StringExt, ValueExt}, + ext_traits::{AsyncExt, StringExt, ValueExt}, }; use diesel_models::encryption::Encryption; use error_stack::{IntoReport, ResultExt}; @@ -19,6 +19,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, enums as api_enums}, domain::{ @@ -184,6 +185,10 @@ pub async fn save_payout_data_to_locker( card_exp_month: card.expiry_month.to_owned(), card_exp_year: card.expiry_year.to_owned(), nick_name: None, + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, }; let payload = StoreLockerReq::LockerCard(StoreCardReq { merchant_id: &merchant_account.merchant_id, @@ -267,20 +272,65 @@ pub async fn save_payout_data_to_locker( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in saved payout method")?; - let pm_data = api::payment_methods::PaymentMethodsData::Card( - api::payment_methods::CardDetailsPaymentMethod { - last4_digits: card_details - .as_ref() - .map(|c| c.card_number.clone().get_last4()), - issuer_country: None, - expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), - expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), - nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), - card_holder_name: card_details - .as_ref() - .and_then(|c| c.card_holder_name.clone()), - }, - ); + // fetch card info from db + let card_isin = card_details + .as_ref() + .map(|c| c.card_number.clone().get_card_isin()); + + let pm_data = card_isin + .clone() + .async_and_then(|card_isin| async move { + db.get_card_info(&card_isin) + .await + .map_err(|error| services::logger::warn!(card_info_error=?error)) + .ok() + }) + .await + .flatten() + .map(|card_info| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: card_info.card_issuing_country, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: card_info.card_issuer, + card_network: card_info.card_network, + card_type: card_info.card_type, + saved_to_locker: true, + }, + ) + }) + .unwrap_or_else(|| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: None, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, + }, + ) + }); let card_details_encrypted = cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await; diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 4354a3ee195..f291d1cd2e8 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -421,6 +421,7 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: api_models::webhooks::IncomingWebhookEvent, @@ -464,8 +465,12 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandates_response = Box::new( - api::mandates::MandateResponse::from_db_mandate(&state, updated_mandate.clone()) - .await?, + api::mandates::MandateResponse::from_db_mandate( + &state, + key_store, + updated_mandate.clone(), + ) + .await?, ); let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); if let Some(outgoing_event_type) = event_type { @@ -1237,6 +1242,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr state.clone(), merchant_account, business_profile, + key_store, webhook_details, source_verified, event_type, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 2592d8837d5..e7a0804500c 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -226,7 +226,12 @@ pub async fn get_customer_mandates( &req, customer_id, |state, auth, req| { - crate::core::mandate::get_customer_mandates(state, auth.merchant_account, req) + crate::core::mandate::get_customer_mandates( + state, + auth.merchant_account, + auth.key_store, + req, + ) }, auth::auth_type( &auth::ApiKeyAuth, diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index ecc89a10fa2..468d202b94c 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -41,7 +41,7 @@ pub async fn get_mandate( state, &req, mandate_id, - |state, auth, req| mandate::get_mandate(state, auth.merchant_account, req), + |state, auth, req| mandate::get_mandate(state, auth.merchant_account, auth.key_store, req), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) @@ -123,7 +123,9 @@ pub async fn retrieve_mandates_list( state, &req, payload, - |state, auth, req| mandate::retrieve_mandates_list(state, auth.merchant_account, req), + |state, auth, req| { + mandate::retrieve_mandates_list(state, auth.merchant_account, auth.key_store, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::MandateRead), diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index a6eeeabd687..6ef5de886be 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -242,7 +242,7 @@ pub async fn payment_method_retrieve_api( state, &req, payload, - |state, _auth, pm| cards::retrieve_payment_method(state, pm), + |state, auth, pm| cards::retrieve_payment_method(state, pm, auth.key_store), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 8d6b9a15e3a..f6b2d7bba93 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -1,6 +1,7 @@ use api_models::mandates; pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use error_stack::ResultExt; +use masking::PeekInterface; use serde::{Deserialize, Serialize}; use crate::{ @@ -11,7 +12,7 @@ use crate::{ newtype, routes::AppState, types::{ - api, + api, domain, storage::{self, enums as storage_enums}, }, }; @@ -23,12 +24,20 @@ newtype!( #[async_trait::async_trait] pub(crate) trait MandateResponseExt: Sized { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self>; + async fn from_db_mandate( + state: &AppState, + key_store: domain::MerchantKeyStore, + mandate: storage::Mandate, + ) -> RouterResult<Self>; } #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self> { + async fn from_db_mandate( + state: &AppState, + key_store: domain::MerchantKeyStore, + mandate: storage::Mandate, + ) -> RouterResult<Self> { let db = &*state.store; let payment_method = db .find_payment_method(&mandate.payment_method_id) @@ -36,21 +45,35 @@ impl MandateResponseExt for MandateResponse { .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let card = if payment_method.payment_method == storage_enums::PaymentMethod::Card { - let card = payment_methods::cards::get_card_from_locker( - state, - &payment_method.customer_id, - &payment_method.merchant_id, - &payment_method.payment_method_id, - ) - .await?; - let card_detail = payment_methods::transformers::get_card_detail(&payment_method, card) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting card details")?; - Some(MandateCardDetails::from(card_detail).into_inner()) + // if locker is disabled , decrypt the payment method data + let card_details = if state.conf.locker.locker_enabled { + let card = payment_methods::cards::get_card_from_locker( + state, + &payment_method.customer_id, + &payment_method.merchant_id, + &payment_method.payment_method_id, + ) + .await?; + + payment_methods::transformers::get_card_detail(&payment_method, card) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting card details")? + } else { + payment_methods::cards::get_card_details_without_locker_fallback( + &payment_method, + key_store.key.get_inner().peek(), + state, + ) + .await? + }; + + Some(MandateCardDetails::from(card_details).into_inner()) } else { None }; - + let payment_method_type = payment_method + .payment_method_type + .map(|pmt| pmt.to_string()); Ok(Self { mandate_id: mandate.mandate_id, customer_acceptance: Some(api::payments::CustomerAcceptance { @@ -68,6 +91,7 @@ impl MandateResponseExt for MandateResponse { card, status: mandate.mandate_status, payment_method: payment_method.payment_method.to_string(), + payment_method_type, payment_method_id: mandate.payment_method_id, }) } @@ -84,6 +108,10 @@ impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { scheme: card_details_from_locker.scheme, issuer_country: card_details_from_locker.issuer_country, card_fingerprint: card_details_from_locker.card_fingerprint, + card_isin: card_details_from_locker.card_isin, + card_issuer: card_details_from_locker.card_issuer, + card_network: card_details_from_locker.card_network, + card_type: card_details_from_locker.card_type, } .into() } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 358a591a667..268ebd1d3ac 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -33,6 +33,7 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true [forex_api] call_delay = 21600 diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index b2f5d3ea52c..02df6324a06 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4421,11 +4421,37 @@ "description": "Card Holder's Nick Name", "example": "John Doe", "nullable": true + }, + "card_issuing_country": { + "type": "string", + "description": "Card Issuing Country", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "Issuer Bank for Card", + "nullable": true + }, + "card_type": { + "type": "string", + "description": "Card Type", + "nullable": true } } }, "CardDetailFromLocker": { "type": "object", + "required": [ + "saved_to_locker" + ], "properties": { "scheme": { "type": "string", @@ -4462,6 +4488,29 @@ "nick_name": { "type": "string", "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_isin": { + "type": "string", + "nullable": true + }, + "card_issuer": { + "type": "string", + "nullable": true + }, + "card_type": { + "type": "string", + "nullable": true + }, + "saved_to_locker": { + "type": "boolean" } } }, @@ -6884,6 +6933,29 @@ "type": "string", "description": "A unique identifier alias to identify a particular card", "nullable": true + }, + "card_isin": { + "type": "string", + "description": "The first 6 digits of card", + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "The bank that issued the card", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "description": "The type of the payment card", + "nullable": true } } }, @@ -6932,6 +7004,11 @@ "type": "string", "description": "The payment method" }, + "payment_method_type": { + "type": "string", + "description": "The payment method type", + "nullable": true + }, "card": { "allOf": [ {
2024-01-15T11:31:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add locker config to enable or disable locker , so that if the locker is enabled we can store the card_details in the locker else if the config is disabled we don't Also this PR involvesaddition in the `MandateResponse`. ### 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 Feature provides an option for the merchant whether or not to save the card at hyperswitch . Saving the card at hyperswitch is not necessary if the mandate is created at the processor level. ## How did you test it? - Create an MA & MCA - Disable the `locker_enabled` config > Create a Mandate payment , the details will not be stored in Locker and payment will be successful > List PaymentMethods for a Customer won't have any details as the card was never stored > List the Mandates would have mandate details ![Screenshot 2024-01-16 at 4 38 43 PM](https://github.com/juspay/hyperswitch/assets/55580080/c9d5d11b-b31f-4a58-a324-f92c376a7c26) ![Screenshot 2024-01-16 at 4 38 59 PM](https://github.com/juspay/hyperswitch/assets/55580080/32645dfa-c962-43a2-9e7f-ca1056415560) ![Screenshot 2024-01-16 at 4 39 10 PM](https://github.com/juspay/hyperswitch/assets/55580080/f413bd94-b74c-4a1b-bf22-fbc335a05e56) ![Screenshot 2024-01-16 at 4 39 26 PM](https://github.com/juspay/hyperswitch/assets/55580080/2745fabd-bc81-4d2b-ab53-d6829fa53d13) ![Screenshot 2024-01-16 at 4 39 38 PM](https://github.com/juspay/hyperswitch/assets/55580080/25221f1c-7932-4295-9a6e-083355513c15) - Enable the `locker_enabled` config > Create a Mandate payment , the details will be stored in Locker and payment will be successful > List PaymentMethods for a Customer would have details of the card that was stored > List the Mandates ![Screenshot 2024-01-16 at 4 33 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/174a1933-9112-4088-893c-12c4e84b3148) ![Screenshot 2024-01-16 at 4 34 57 PM](https://github.com/juspay/hyperswitch/assets/55580080/2a5f46e7-86b0-470e-89a6-3a8f0a225c3b) ![Screenshot 2024-01-16 at 4 35 18 PM](https://github.com/juspay/hyperswitch/assets/55580080/66a1df1f-0f8a-418e-a122-570508eb97a9) ![Screenshot 2024-01-16 at 4 35 33 PM](https://github.com/juspay/hyperswitch/assets/55580080/8c5fe598-9cad-498f-88eb-ef9ca0c3018b) ![Screenshot 2024-01-16 at 4 35 51 PM](https://github.com/juspay/hyperswitch/assets/55580080/8d05dbcb-ef2d-4c2a-b326-56393ed5b16e) ![Screenshot 2024-01-16 at 4 36 32 PM](https://github.com/juspay/hyperswitch/assets/55580080/0e3e9272-27b5-44de-9c3a-4e1e942faee9) -When we do a list mandates we have an additional field `payment_method_type` ![Screenshot 2024-01-18 at 4 27 53 PM](https://github.com/juspay/hyperswitch/assets/55580080/7b2455e7-889b-4e01-979d-56353ce60f49) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2f693ad1fd857280ef30c6cc0297fb926f0e79e8
juspay/hyperswitch
juspay__hyperswitch-3338
Bug: [REFACTOR] Enable runtime flag for `s3` feature ### Feature Description Tracking issue for refactoring `s3` to include compile time + runtime time flag Current implementation - We are building 2 docker images, one image contains all the release features including `kms`, `s3`, etc and other without these features which are getting pushed to the public docker hub. This was to ensure that anyone who wants to try out Hyperswitch locally by pulling the pre-built docker image, it shouldn't be a hassle for he/she to setup `s3`. For this very reason we were pushing 2 docker images which was a temporary solution ### Possible Implementation Providing support for enabling or disabling s3 feature in runtime so that we no longer have to build 2 images. ### Tasks - [x] #3340 - [x] #3347 ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index f920b1ea9c5..b86facad816 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2481,6 +2481,7 @@ dependencies = [ "async-trait", "aws-config", "aws-sdk-kms", + "aws-sdk-s3", "aws-sdk-sesv2", "aws-sdk-sts", "aws-smithy-client", @@ -2726,9 +2727,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -2736,9 +2737,9 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" @@ -2764,9 +2765,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-lite" @@ -2785,9 +2786,9 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", @@ -2796,15 +2797,15 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-timer" @@ -2814,9 +2815,9 @@ checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" [[package]] name = "futures-util" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -5155,8 +5156,6 @@ dependencies = [ "async-bb8-diesel", "async-trait", "awc", - "aws-config", - "aws-sdk-s3", "base64 0.21.5", "bb8", "bigdecimal", diff --git a/config/config.example.toml b/config/config.example.toml index 0ad50736e9e..27d1f8b18c5 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -535,3 +535,11 @@ refund_analytics_topic = "topic" # Kafka topic to be used for Refund events api_logs_topic = "topic" # Kafka topic to be used for incoming api events connector_logs_topic = "topic" # Kafka topic to be used for connector api events outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events + +# File storage configuration +[file_storage] +file_storage_backend = "aws_s3" # File storage backend to be used + +[file_storage.aws_s3] +region = "us-east-1" # The AWS region used by the AWS S3 for file storage +bucket_name = "bucket1" # The AWS S3 bucket name for file storage diff --git a/config/development.toml b/config/development.toml index b23f68680e6..5fbe9607cd3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -544,3 +544,6 @@ client_id = "" client_secret = "" partner_id = "" enabled = true + +[file_storage] +file_storage_backend = "file_system" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8af1528e177..8dd01a3d1ce 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -399,3 +399,6 @@ enabled = true [events] source = "logs" + +[file_storage] +file_storage_backend = "file_system" diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 6552b57b0e5..bf836af71a7 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [features] kms = ["dep:aws-config", "dep:aws-sdk-kms"] email = ["dep:aws-config"] +aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = [ "dep:vaultrs" ] [dependencies] @@ -18,6 +19,7 @@ aws-config = { version = "0.55.3", optional = true } aws-sdk-kms = { version = "0.28.0", optional = true } aws-sdk-sesv2 = "0.28.0" aws-sdk-sts = "0.28.0" +aws-sdk-s3 = { version = "0.28.0", optional = true } aws-smithy-client = "0.55.3" base64 = "0.21.2" dyn-clone = "1.0.11" diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs new file mode 100644 index 00000000000..fb419b6ec64 --- /dev/null +++ b/crates/external_services/src/file_storage.rs @@ -0,0 +1,96 @@ +//! +//! Module for managing file storage operations with support for multiple storage schemes. +//! + +use std::fmt::{Display, Formatter}; + +use common_utils::errors::CustomResult; + +/// Includes functionality for AWS S3 storage operations. +#[cfg(feature = "aws_s3")] +mod aws_s3; + +mod file_system; + +/// Enum representing different file storage configurations, allowing for multiple storage schemes. +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(tag = "file_storage_backend")] +#[serde(rename_all = "snake_case")] +pub enum FileStorageConfig { + /// AWS S3 storage configuration. + #[cfg(feature = "aws_s3")] + AwsS3 { + /// Configuration for AWS S3 file storage. + aws_s3: aws_s3::AwsFileStorageConfig, + }, + /// Local file system storage configuration. + #[default] + FileSystem, +} + +impl FileStorageConfig { + /// Validates the file storage configuration. + pub fn validate(&self) -> Result<(), InvalidFileStorageConfig> { + match self { + #[cfg(feature = "aws_s3")] + Self::AwsS3 { aws_s3 } => aws_s3.validate(), + Self::FileSystem => Ok(()), + } + } + + /// Retrieves the appropriate file storage client based on the file storage configuration. + pub async fn get_file_storage_client(&self) -> Box<dyn FileStorageInterface> { + match self { + #[cfg(feature = "aws_s3")] + Self::AwsS3 { aws_s3 } => Box::new(aws_s3::AwsFileStorageClient::new(aws_s3).await), + Self::FileSystem => Box::new(file_system::FileSystem), + } + } +} + +/// Trait for file storage operations +#[async_trait::async_trait] +pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send { + /// Uploads a file to the selected storage scheme. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError>; + + /// Deletes a file from the selected storage scheme. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError>; + + /// Retrieves a file from the selected storage scheme. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError>; +} + +dyn_clone::clone_trait_object!(FileStorageInterface); + +/// Error thrown when the file storage config is invalid +#[derive(Debug, Clone)] +pub struct InvalidFileStorageConfig(&'static str); + +impl std::error::Error for InvalidFileStorageConfig {} + +impl Display for InvalidFileStorageConfig { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "file_storage: {}", self.0) + } +} + +/// Represents errors that can occur during file storage operations. +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum FileStorageError { + /// Indicates that the file upload operation failed. + #[error("Failed to upload file")] + UploadFailed, + + /// Indicates that the file retrieval operation failed. + #[error("Failed to retrieve file")] + RetrieveFailed, + + /// Indicates that the file deletion operation failed. + #[error("Failed to delete file")] + DeleteFailed, +} diff --git a/crates/external_services/src/file_storage/aws_s3.rs b/crates/external_services/src/file_storage/aws_s3.rs new file mode 100644 index 00000000000..86d1c0f0efa --- /dev/null +++ b/crates/external_services/src/file_storage/aws_s3.rs @@ -0,0 +1,158 @@ +use aws_config::meta::region::RegionProviderChain; +use aws_sdk_s3::{ + operation::{ + delete_object::DeleteObjectError, get_object::GetObjectError, put_object::PutObjectError, + }, + Client, +}; +use aws_sdk_sts::config::Region; +use common_utils::{errors::CustomResult, ext_traits::ConfigExt}; +use error_stack::ResultExt; + +use super::InvalidFileStorageConfig; +use crate::file_storage::{FileStorageError, FileStorageInterface}; + +/// Configuration for AWS S3 file storage. +#[derive(Debug, serde::Deserialize, Clone, Default)] +#[serde(default)] +pub struct AwsFileStorageConfig { + /// The AWS region to send file uploads + region: String, + /// The AWS s3 bucket to send file uploads + bucket_name: String, +} + +impl AwsFileStorageConfig { + /// Validates the AWS S3 file storage configuration. + pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> { + use common_utils::fp_utils::when; + + when(self.region.is_default_or_empty(), || { + Err(InvalidFileStorageConfig("aws s3 region must not be empty")) + })?; + + when(self.bucket_name.is_default_or_empty(), || { + Err(InvalidFileStorageConfig( + "aws s3 bucket name must not be empty", + )) + }) + } +} + +/// AWS S3 file storage client. +#[derive(Debug, Clone)] +pub(super) struct AwsFileStorageClient { + /// AWS S3 client + inner_client: Client, + /// The name of the AWS S3 bucket. + bucket_name: String, +} + +impl AwsFileStorageClient { + /// Creates a new AWS S3 file storage client. + pub(super) async fn new(config: &AwsFileStorageConfig) -> Self { + let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone())); + let sdk_config = aws_config::from_env().region(region_provider).load().await; + Self { + inner_client: Client::new(&sdk_config), + bucket_name: config.bucket_name.clone(), + } + } + + /// Uploads a file to AWS S3. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), AwsS3StorageError> { + self.inner_client + .put_object() + .bucket(&self.bucket_name) + .key(file_key) + .body(file.into()) + .send() + .await + .map_err(AwsS3StorageError::UploadFailure)?; + Ok(()) + } + + /// Deletes a file from AWS S3. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), AwsS3StorageError> { + self.inner_client + .delete_object() + .bucket(&self.bucket_name) + .key(file_key) + .send() + .await + .map_err(AwsS3StorageError::DeleteFailure)?; + Ok(()) + } + + /// Retrieves a file from AWS S3. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, AwsS3StorageError> { + Ok(self + .inner_client + .get_object() + .bucket(&self.bucket_name) + .key(file_key) + .send() + .await + .map_err(AwsS3StorageError::RetrieveFailure)? + .body + .collect() + .await + .map_err(AwsS3StorageError::UnknownError)? + .to_vec()) + } +} + +#[async_trait::async_trait] +impl FileStorageInterface for AwsFileStorageClient { + /// Uploads a file to AWS S3. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError> { + self.upload_file(file_key, file) + .await + .change_context(FileStorageError::UploadFailed)?; + Ok(()) + } + + /// Deletes a file from AWS S3. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> { + self.delete_file(file_key) + .await + .change_context(FileStorageError::DeleteFailed)?; + Ok(()) + } + + /// Retrieves a file from AWS S3. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> { + Ok(self + .retrieve_file(file_key) + .await + .change_context(FileStorageError::RetrieveFailed)?) + } +} + +/// Enum representing errors that can occur during AWS S3 file storage operations. +#[derive(Debug, thiserror::Error)] +enum AwsS3StorageError { + /// Error indicating that file upload to S3 failed. + #[error("File upload to S3 failed: {0:?}")] + UploadFailure(aws_smithy_client::SdkError<PutObjectError>), + + /// Error indicating that file retrieval from S3 failed. + #[error("File retrieve from S3 failed: {0:?}")] + RetrieveFailure(aws_smithy_client::SdkError<GetObjectError>), + + /// Error indicating that file deletion from S3 failed. + #[error("File delete from S3 failed: {0:?}")] + DeleteFailure(aws_smithy_client::SdkError<DeleteObjectError>), + + /// Unknown error occurred. + #[error("Unknown error occurred: {0:?}")] + UnknownError(aws_sdk_s3::primitives::ByteStreamError), +} diff --git a/crates/external_services/src/file_storage/file_system.rs b/crates/external_services/src/file_storage/file_system.rs new file mode 100644 index 00000000000..15ca84deeb8 --- /dev/null +++ b/crates/external_services/src/file_storage/file_system.rs @@ -0,0 +1,144 @@ +//! +//! Module for local file system storage operations +//! + +use std::{ + fs::{remove_file, File}, + io::{Read, Write}, + path::PathBuf, +}; + +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; + +use crate::file_storage::{FileStorageError, FileStorageInterface}; + +/// Constructs the file path for a given file key within the file system. +/// The file path is generated based on the workspace path and the provided file key. +fn get_file_path(file_key: impl AsRef<str>) -> PathBuf { + let mut file_path = PathBuf::new(); + #[cfg(feature = "logs")] + file_path.push(router_env::env::workspace_path()); + #[cfg(not(feature = "logs"))] + file_path.push(std::env::current_dir().unwrap_or(".".into())); + + file_path.push("files"); + file_path.push(file_key.as_ref()); + file_path +} + +/// Represents a file system for storing and managing files locally. +#[derive(Debug, Clone)] +pub(super) struct FileSystem; + +impl FileSystem { + /// Saves the provided file data to the file system under the specified file key. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileSystemStorageError> { + let file_path = get_file_path(file_key); + + // Ignore the file name and create directories in the `file_path` if not exists + std::fs::create_dir_all( + file_path + .parent() + .ok_or(FileSystemStorageError::CreateDirFailed) + .into_report() + .attach_printable("Failed to obtain parent directory")?, + ) + .into_report() + .change_context(FileSystemStorageError::CreateDirFailed)?; + + let mut file_handler = File::create(file_path) + .into_report() + .change_context(FileSystemStorageError::CreateFailure)?; + file_handler + .write_all(&file) + .into_report() + .change_context(FileSystemStorageError::WriteFailure)?; + Ok(()) + } + + /// Deletes the file associated with the specified file key from the file system. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileSystemStorageError> { + let file_path = get_file_path(file_key); + remove_file(file_path) + .into_report() + .change_context(FileSystemStorageError::DeleteFailure)?; + Ok(()) + } + + /// Retrieves the file content associated with the specified file key from the file system. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileSystemStorageError> { + let mut received_data: Vec<u8> = Vec::new(); + let file_path = get_file_path(file_key); + let mut file = File::open(file_path) + .into_report() + .change_context(FileSystemStorageError::FileOpenFailure)?; + file.read_to_end(&mut received_data) + .into_report() + .change_context(FileSystemStorageError::ReadFailure)?; + Ok(received_data) + } +} + +#[async_trait::async_trait] +impl FileStorageInterface for FileSystem { + /// Saves the provided file data to the file system under the specified file key. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError> { + self.upload_file(file_key, file) + .await + .change_context(FileStorageError::UploadFailed)?; + Ok(()) + } + + /// Deletes the file associated with the specified file key from the file system. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> { + self.delete_file(file_key) + .await + .change_context(FileStorageError::DeleteFailed)?; + Ok(()) + } + + /// Retrieves the file content associated with the specified file key from the file system. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> { + Ok(self + .retrieve_file(file_key) + .await + .change_context(FileStorageError::RetrieveFailed)?) + } +} + +/// Represents an error that can occur during local file system storage operations. +#[derive(Debug, thiserror::Error)] +enum FileSystemStorageError { + /// Error indicating opening a file failed + #[error("Failed while opening the file")] + FileOpenFailure, + + /// Error indicating file creation failed. + #[error("Failed to create file")] + CreateFailure, + + /// Error indicating reading a file failed. + #[error("Failed while reading the file")] + ReadFailure, + + /// Error indicating writing to a file failed. + #[error("Failed while writing into file")] + WriteFailure, + + /// Error indicating file deletion failed. + #[error("Failed while deleting the file")] + DeleteFailure, + + /// Error indicating directory creation failed + #[error("Failed while creating a directory")] + CreateDirFailed, +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 9bf4916eec3..bba65873e91 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -9,6 +9,7 @@ pub mod email; #[cfg(feature = "kms")] pub mod kms; +pub mod file_storage; #[cfg(feature = "hashicorp-vault")] pub mod hashicorp_vault; diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e575daf7e7a..3d129edfe3f 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,10 +10,10 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] -aws_s3 = ["dep:aws-sdk-s3", "dep:aws-config"] -kms = ["external_services/kms", "dep:aws-config"] +aws_s3 = ["external_services/aws_s3"] +kms = ["external_services/kms"] hashicorp-vault = ["external_services/hashicorp-vault"] -email = ["external_services/email", "dep:aws-config", "olap"] +email = ["external_services/email", "olap"] frm = [] stripe = ["dep:serde_qs"] release = ["kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] @@ -42,8 +42,6 @@ actix-web = "4.3.1" async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } argon2 = { version = "0.5.0", features = ["std"] } async-trait = "0.1.68" -aws-config = { version = "0.55.3", optional = true } -aws-sdk-s3 = { version = "0.28.0", optional = true } base64 = "0.21.2" bb8 = "0.8" bigdecimal = "0.3.1" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3c1d9f7d397..146a1ace28e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -11,6 +11,7 @@ use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; #[cfg(feature = "email")] use external_services::email::EmailSettings; +use external_services::file_storage::FileStorageConfig; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; #[cfg(feature = "kms")] @@ -90,10 +91,9 @@ pub struct Settings { pub api_keys: ApiKeys, #[cfg(feature = "kms")] pub kms: kms::KmsConfig, + pub file_storage: FileStorageConfig, #[cfg(feature = "hashicorp-vault")] pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, - #[cfg(feature = "aws_s3")] - pub file_upload_config: FileUploadConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] @@ -721,16 +721,6 @@ pub struct ApiKeys { pub expiry_reminder_days: Vec<u8>, } -#[cfg(feature = "aws_s3")] -#[derive(Debug, Deserialize, Clone, Default)] -#[serde(default)] -pub struct FileUploadConfig { - /// The AWS region to send file uploads - pub region: String, - /// The AWS s3 bucket to send file uploads - pub bucket_name: String, -} - #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { #[serde(deserialize_with = "deser_to_get_connectors")] @@ -853,8 +843,11 @@ impl Settings { self.kms .validate() .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; - #[cfg(feature = "aws_s3")] - self.file_upload_config.validate()?; + + self.file_storage + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + self.lock_settings.validate()?; self.events.validate()?; Ok(()) diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 0b286ece843..910ae754347 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -127,25 +127,6 @@ impl super::settings::DrainerSettings { } } -#[cfg(feature = "aws_s3")] -impl super::settings::FileUploadConfig { - pub fn validate(&self) -> Result<(), ApplicationError> { - use common_utils::fp_utils::when; - - when(self.region.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "s3 region must not be empty".into(), - )) - })?; - - when(self.bucket_name.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "s3 bucket name must not be empty".into(), - )) - }) - } -} - impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index f3e56489806..d3f490a0a6c 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -1,9 +1,4 @@ pub mod helpers; -#[cfg(feature = "aws_s3")] -pub mod s3_utils; - -#[cfg(not(feature = "aws_s3"))] -pub mod fs_utils; use api_models::files; use error_stack::{IntoReport, ResultExt}; @@ -29,10 +24,7 @@ pub async fn files_create_core( ) .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); - #[cfg(feature = "aws_s3")] let file_key = format!("{}/{}", merchant_account.merchant_id, file_id); - #[cfg(not(feature = "aws_s3"))] - let file_key = format!("{}_{}", merchant_account.merchant_id, file_id); let file_new = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), merchant_id: merchant_account.merchant_id.clone(), diff --git a/crates/router/src/core/files/fs_utils.rs b/crates/router/src/core/files/fs_utils.rs deleted file mode 100644 index 795f2fad759..00000000000 --- a/crates/router/src/core/files/fs_utils.rs +++ /dev/null @@ -1,57 +0,0 @@ -use std::{ - fs::{remove_file, File}, - io::{Read, Write}, - path::PathBuf, -}; - -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; - -use crate::{core::errors, env}; - -pub fn get_file_path(file_key: String) -> PathBuf { - let mut file_path = PathBuf::new(); - file_path.push(env::workspace_path()); - file_path.push("files"); - file_path.push(file_key); - file_path -} - -pub fn save_file_to_fs( - file_key: String, - file_data: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let file_path = get_file_path(file_key); - let mut file = File::create(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to create file")?; - file.write_all(&file_data) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while writing into file")?; - Ok(()) -} - -pub fn delete_file_from_fs(file_key: String) -> CustomResult<(), errors::ApiErrorResponse> { - let file_path = get_file_path(file_key); - remove_file(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while deleting the file")?; - Ok(()) -} - -pub fn retrieve_file_from_fs(file_key: String) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - let mut received_data: Vec<u8> = Vec::new(); - let file_path = get_file_path(file_key); - let mut file = File::open(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while opening the file")?; - file.read_to_end(&mut received_data) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while reading the file")?; - Ok(received_data) -} diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 9205d42aeee..0a509b238af 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -6,7 +6,7 @@ use futures::TryStreamExt; use crate::{ core::{ errors::{self, StorageErrorExt}, - files, payments, utils, + payments, utils, }, routes::AppState, services, @@ -30,37 +30,6 @@ pub async fn get_file_purpose(field: &mut Field) -> Option<api::FilePurpose> { } } -pub async fn upload_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, - file: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::upload_file_to_s3(state, file_key, file).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::save_file_to_fs(file_key, file); -} - -pub async fn delete_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, -) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::delete_file_from_s3(state, file_key).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::delete_file_from_fs(file_key); -} - -pub async fn retrieve_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, -) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::retrieve_file_from_s3(state, file_key).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::retrieve_file_from_fs(file_key); -} - pub async fn validate_file_upload( state: &AppState, merchant_account: domain::MerchantAccount, @@ -132,14 +101,11 @@ pub async fn delete_file_using_file_id( .attach_printable("File not available")?, }; match provider { - diesel_models::enums::FileUploadProvider::Router => { - delete_file( - #[cfg(feature = "aws_s3")] - state, - provider_file_id, - ) + diesel_models::enums::FileUploadProvider::Router => state + .file_storage_client + .delete_file(&provider_file_id) .await - } + .change_context(errors::ApiErrorResponse::InternalServerError), _ => Err(errors::ApiErrorResponse::FileProviderNotSupported { message: "Not Supported because provider is not Router".to_string(), } @@ -234,12 +200,11 @@ pub async fn retrieve_file_and_provider_file_id_from_file_id( match provider { diesel_models::enums::FileUploadProvider::Router => Ok(( Some( - retrieve_file( - #[cfg(feature = "aws_s3")] - state, - provider_file_id.clone(), - ) - .await?, + state + .file_storage_client + .retrieve_file(&provider_file_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?, ), Some(provider_file_id), )), @@ -364,13 +329,11 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( payment_attempt.merchant_connector_id, )) } else { - upload_file( - #[cfg(feature = "aws_s3")] - state, - file_key.clone(), - create_file_request.file.clone(), - ) - .await?; + state + .file_storage_client + .upload_file(&file_key, create_file_request.file.clone()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(( file_key, api_models::enums::FileUploadProvider::Router, diff --git a/crates/router/src/core/files/s3_utils.rs b/crates/router/src/core/files/s3_utils.rs deleted file mode 100644 index 228c23528cd..00000000000 --- a/crates/router/src/core/files/s3_utils.rs +++ /dev/null @@ -1,87 +0,0 @@ -use aws_config::{self, meta::region::RegionProviderChain}; -use aws_sdk_s3::{config::Region, Client}; -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; -use futures::TryStreamExt; - -use crate::{core::errors, routes}; - -async fn get_aws_client(state: &routes::AppState) -> Client { - let region_provider = - RegionProviderChain::first_try(Region::new(state.conf.file_upload_config.region.clone())); - let sdk_config = aws_config::from_env().region(region_provider).load().await; - Client::new(&sdk_config) -} - -pub async fn upload_file_to_s3( - state: &routes::AppState, - file_key: String, - file: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Upload file to S3 - let upload_res = client - .put_object() - .bucket(bucket_name) - .key(file_key.clone()) - .body(file.into()) - .send() - .await; - upload_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File upload to S3 failed")?; - Ok(()) -} - -pub async fn delete_file_from_s3( - state: &routes::AppState, - file_key: String, -) -> CustomResult<(), errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Delete file from S3 - let delete_res = client - .delete_object() - .bucket(bucket_name) - .key(file_key) - .send() - .await; - delete_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File delete from S3 failed")?; - Ok(()) -} - -pub async fn retrieve_file_from_s3( - state: &routes::AppState, - file_key: String, -) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Get file data from S3 - let get_res = client - .get_object() - .bucket(bucket_name) - .key(file_key) - .send() - .await; - let mut object = get_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File retrieve from S3 failed")?; - let mut received_data: Vec<u8> = Vec::new(); - while let Some(bytes) = object - .body - .try_next() - .await - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid file data received from S3")? - { - received_data.extend_from_slice(&bytes); // Collect the bytes in the Vec - } - Ok(received_data) -} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f490cee8dab..2b26a5e7586 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -5,6 +5,7 @@ use actix_web::{web, Scope}; use analytics::AnalyticsConfig; #[cfg(feature = "email")] use external_services::email::{ses::AwsSes, EmailService}; +use external_services::file_storage::FileStorageInterface; #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] use external_services::hashicorp_vault::decrypt::VaultFetch; #[cfg(feature = "kms")] @@ -68,6 +69,7 @@ pub struct AppState { #[cfg(feature = "olap")] pub pool: crate::analytics::AnalyticsProvider, pub request_id: Option<RequestId>, + pub file_storage_client: Box<dyn FileStorageInterface>, } impl scheduler::SchedulerAppState for AppState { @@ -266,6 +268,8 @@ impl AppState { #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await); + let file_storage_client = conf.file_storage.get_file_storage_client().await; + Self { flow_name: String::from("default"), store, @@ -279,6 +283,7 @@ impl AppState { #[cfg(feature = "olap")] pool, request_id: None, + file_storage_client, } }) .await diff --git a/docker-compose.yml b/docker-compose.yml index 3839269a522..e55008f1e34 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -54,6 +54,7 @@ services: - router_net volumes: - ./config:/local/config + - ./files:/local/bin/files labels: logs: "promtail" healthcheck:
2024-01-14T14:27:35Z
## 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 includes refactoring for: * Enabling easy extension of other file storage schemes. * Providing a runtime flag for the file storage feature. * Restrict the file storage objects(structs, methods) visibility wherever possible. ### 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 #3338, Closes #3347 ## 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 dispute and get the `dispute_id` ### File System 1. File uploading ``` curl --location --request POST 'localhost:8080/files' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' \ --header 'Content-Type: multipart/form-data; boundary=6467930559a8e09e-babf866111649afb-06f42165ce9a45a7-bc825186544537e1' \ --header 'Accept-Encoding: gzip' \ --form 'purpose="dispute_evidence"' \ --form 'file=@"/Users/sai.harsha/Desktop/dummy.pdf"' \ --form 'dispute_id="dp_Hv9m2MJGRjptYmEYPqFa"' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/ddec5aff-a0e3-4d09-9d0d-32f698e0c3cc) 2. File retrieve ``` curl --location --request GET 'localhost:8080/files/file_qXP0X6uAgLwSvswj8T41' \ --header 'Accept: application/json' \ --header 'api-key: dev_H3Uf7cssLge9XnWZZfV2M5xwqroMHt46cXh0EwXJQHTdYuBTVC3KVnA5Fo45hagw' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/efe193e3-b5d7-4f30-8546-c499a6c36483) 3. File delete ``` curl --location --request DELETE 'localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/a724d0b7-1c80-4c62-9b2e-2fd20205c681) ### Aws S3 1. File uploading ![image](https://github.com/juspay/hyperswitch/assets/70657455/e4077964-e117-4f50-8e9b-25bdcb794a9a) 2. File retrieve ![image](https://github.com/juspay/hyperswitch/assets/70657455/b7d3e799-0fde-48a2-aac0-513faa49523e) 3. File delete ![image (1)](https://github.com/juspay/hyperswitch/assets/70657455/e398faeb-0697-483c-8a41-dd5bd47d5e18) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3fbffdc242dafe7983c542573b7c6362f99331e6
juspay/hyperswitch
juspay__hyperswitch-3355
Bug: [REFACTOR]: [Cybersource] Recurring Mandates Payments Flow ### Feature Description In recurring subsequent mandate payment (MIT) the payment was getting processed with card fetched from locker, it should being processed with `connector_mandate_id` ### Possible Implementation Implement a check over `connector_mandate_id` rather than checking over Payment Method Data ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index b300e97b44a..ac2d16c9610 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -785,7 +785,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - if req.is_three_ds() && req.request.is_card() { + if req.is_three_ds() + && req.request.is_card() + && req.request.connector_mandate_id().is_none() + { Ok(format!( "{}risk/v1/authentication-setups", api::ConnectorCommon::base_url(self, connectors) @@ -809,7 +812,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.amount, req, ))?; - if req.is_three_ds() && req.request.is_card() { + if req.is_three_ds() + && req.request.is_card() + && req.request.connector_mandate_id().is_none() + { let connector_req = cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -845,7 +851,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - if data.is_three_ds() && data.request.is_card() { + if data.is_three_ds() + && data.request.is_card() + && data.request.connector_mandate_id().is_none() + { let response: cybersource::CybersourceAuthSetupResponse = res .response .parse_struct("Cybersource AuthSetupResponse") diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index e83b23603e9..8beb81d9236 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -342,7 +342,7 @@ pub struct ApplePayPaymentInformation { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MandatePaymentInformation { - payment_instrument: Option<CybersoucrePaymentInstrument>, + payment_instrument: CybersoucrePaymentInstrument, } #[derive(Debug, Serialize)] @@ -482,7 +482,7 @@ impl ), ) -> Self { let (action_list, action_token_types, authorization_options) = - if item.router_data.request.setup_future_usage.is_some() { + if item.router_data.request.setup_mandate_details.is_some() { ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), @@ -871,139 +871,168 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> fn try_from( item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - match item.router_data.request.payment_method_data.clone() { - payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), - payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { - payments::WalletData::ApplePay(apple_pay_data) => { - match item.router_data.payment_method_token.clone() { - Some(payment_method_token) => match payment_method_token { - types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { - Self::try_from((item, decrypt_data)) - } - types::PaymentMethodToken::Token(_) => { - Err(errors::ConnectorError::InvalidWalletToken)? - } - }, - None => { - let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; - let order_information = OrderInformationWithBill::from((item, bill_to)); - let processing_information = ProcessingInformation::from(( - item, - Some(PaymentSolution::ApplePay), - )); - let client_reference_information = - ClientReferenceInformation::from(item); - let payment_information = PaymentInformation::ApplePayToken( - ApplePayTokenPaymentInformation { - fluid_data: FluidData { - value: Secret::from(apple_pay_data.payment_data), - }, - tokenized_card: ApplePayTokenizedCard { - transaction_type: TransactionType::ApplePay, - }, + match item.router_data.request.connector_mandate_id() { + Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)), + None => { + match item.router_data.request.payment_method_data.clone() { + payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + payments::WalletData::ApplePay(apple_pay_data) => { + match item.router_data.payment_method_token.clone() { + Some(payment_method_token) => match payment_method_token { + types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { + Self::try_from((item, decrypt_data)) + } + types::PaymentMethodToken::Token(_) => { + Err(errors::ConnectorError::InvalidWalletToken)? + } }, - ); - let merchant_defined_information = - item.router_data.request.metadata.clone().map(|metadata| { - Vec::<MerchantDefinedInformation>::foreign_from( - metadata.peek().to_owned(), - ) - }); - - Ok(Self { - processing_information, - payment_information, - order_information, - client_reference_information, - merchant_defined_information, - consumer_authentication_information: None, - }) + None => { + let email = item.router_data.request.get_email()?; + let bill_to = + build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = + OrderInformationWithBill::from((item, bill_to)); + let processing_information = ProcessingInformation::from(( + item, + Some(PaymentSolution::ApplePay), + )); + let client_reference_information = + ClientReferenceInformation::from(item); + let payment_information = PaymentInformation::ApplePayToken( + ApplePayTokenPaymentInformation { + fluid_data: FluidData { + value: Secret::from(apple_pay_data.payment_data), + }, + tokenized_card: ApplePayTokenizedCard { + transaction_type: TransactionType::ApplePay, + }, + }, + ); + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from( + metadata.peek().to_owned(), + ) + }); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + consumer_authentication_information: None, + }) + } + } + } + payments::WalletData::GooglePay(google_pay_data) => { + Self::try_from((item, google_pay_data)) } + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayRedirect(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::WeChatPayQr(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message( + "Cybersource", + ), + ) + .into()) + } + }, + // If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause. + // This is a fallback implementation in the event of catastrophe. + payments::PaymentMethodData::MandatePayment => { + let connector_mandate_id = + item.router_data.request.connector_mandate_id().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "connector_mandate_id", + }, + )?; + Self::try_from((item, connector_mandate_id)) + } + payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ) + .into()) } } - payments::WalletData::GooglePay(google_pay_data) => { - Self::try_from((item, google_pay_data)) - } - payments::WalletData::AliPayQr(_) - | payments::WalletData::AliPayRedirect(_) - | payments::WalletData::AliPayHkRedirect(_) - | payments::WalletData::MomoRedirect(_) - | payments::WalletData::KakaoPayRedirect(_) - | payments::WalletData::GoPayRedirect(_) - | payments::WalletData::GcashRedirect(_) - | payments::WalletData::ApplePayRedirect(_) - | payments::WalletData::ApplePayThirdPartySdk(_) - | payments::WalletData::DanaRedirect {} - | payments::WalletData::GooglePayRedirect(_) - | payments::WalletData::GooglePayThirdPartySdk(_) - | payments::WalletData::MbWayRedirect(_) - | payments::WalletData::MobilePayRedirect(_) - | payments::WalletData::PaypalRedirect(_) - | payments::WalletData::PaypalSdk(_) - | payments::WalletData::SamsungPay(_) - | payments::WalletData::TwintRedirect {} - | payments::WalletData::VippsRedirect {} - | payments::WalletData::TouchNGoRedirect(_) - | payments::WalletData::WeChatPayRedirect(_) - | payments::WalletData::WeChatPayQr(_) - | payments::WalletData::CashappQr(_) - | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Cybersource"), - ) - .into()), - }, - payments::PaymentMethodData::MandatePayment => { - let processing_information = ProcessingInformation::from((item, None)); - let payment_instrument = - item.router_data - .request - .connector_mandate_id() - .map(|mandate_token_id| CybersoucrePaymentInstrument { - id: mandate_token_id, - }); - - let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; - let order_information = OrderInformationWithBill::from((item, bill_to)); - let payment_information = - PaymentInformation::MandatePayment(MandatePaymentInformation { - payment_instrument, - }); - let client_reference_information = ClientReferenceInformation::from(item); - let merchant_defined_information = - item.router_data.request.metadata.clone().map(|metadata| { - Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) - }); - Ok(Self { - processing_information, - payment_information, - order_information, - client_reference_information, - merchant_defined_information, - consumer_authentication_information: None, - }) - } - payments::PaymentMethodData::CardRedirect(_) - | payments::PaymentMethodData::PayLater(_) - | payments::PaymentMethodData::BankRedirect(_) - | payments::PaymentMethodData::BankDebit(_) - | payments::PaymentMethodData::BankTransfer(_) - | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) - | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) - | payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Cybersource"), - ) - .into()) } } } } +impl + TryFrom<( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + String, + )> for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, connector_mandate_id): ( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + String, + ), + ) -> Result<Self, Self::Error> { + let processing_information = ProcessingInformation::from((item, None)); + let payment_instrument = CybersoucrePaymentInstrument { + id: connector_mandate_id, + }; + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + let payment_information = + PaymentInformation::MandatePayment(MandatePaymentInformation { payment_instrument }); + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + consumer_authentication_information: None, + }) + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAuthSetupRequest { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 9eb06d675a0..ad463fcf2b9 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1524,12 +1524,12 @@ pub fn build_redirection_form( // This is the iframe recommended by cybersource but the redirection happens inside this iframe once otp // is received and we lose control of the redirection on user client browser, so to avoid that we have removed this iframe and directly consumed it. // (PreEscaped(r#"<iframe id="step_up_iframe" style="border: none; margin-left: auto; margin-right: auto; display: block" height="800px" width="400px" name="stepUpIframe"></iframe>"#)) - (PreEscaped(format!("<form id=\"step_up_form\" method=\"POST\" action=\"{step_up_url}\"> - <input id=\"step_up_form_jwt_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> + (PreEscaped(format!("<form id=\"step-up-form\" method=\"POST\" action=\"{step_up_url}\"> + <input type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> </form>"))) (PreEscaped(r#"<script> window.onload = function() { - var stepUpForm = document.querySelector('#step_up_form'); if(stepUpForm) stepUpForm.submit(); + var stepUpForm = document.querySelector('#step-up-form'); if(stepUpForm) stepUpForm.submit(); } </script>"#)) }}
2024-01-16T05:35:03Z
## 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 recurring subsequent mandate payment (MIT) the payment was getting processed with card fetched from locker, now it is being processed with `connector_mandate_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 CIT with zero and non-zero amount <img width="1296" alt="Screenshot 2024-01-16 at 11 06 18 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/e746049b-257e-4808-9587-583b7b2c78ef"> <img width="1285" alt="Screenshot 2024-01-16 at 11 06 50 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/38888a7c-89ee-4e28-826f-f600a4c2780d"> - Create MIT using Mandate ID <img width="1278" alt="Screenshot 2024-01-16 at 11 10 41 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/04139f77-8628-4479-8a4d-15cd3f9d9aed"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
398c5ed51e0547504c3dfbd1d7c23568337e7d1c
juspay/hyperswitch
juspay__hyperswitch-3339
Bug: Event Viewer - Add payment_id to PaymentsList API call `PaymentsList` Api call currently does not extract the payment id from payload. Since this API is associated with a payment, we need to add a `payment_id` field to this API call as well
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 26a9d222d6b..3eb19fcc3d8 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -37,7 +37,6 @@ impl ApiEventMetric for TimeRange {} impl_misc_api_event_type!( PaymentMethodId, PaymentsSessionResponse, - PaymentMethodListResponse, PaymentMethodCreate, PaymentLinkInitiateRequest, RetrievePaymentLinkResponse, diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index f718dc1ca4d..32d3dc30bd8 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -3,7 +3,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::{ payment_methods::{ CustomerPaymentMethodsListResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest, - PaymentMethodResponse, PaymentMethodUpdate, + PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters, @@ -119,6 +119,8 @@ impl ApiEventMetric for PaymentMethodListRequest { } } +impl ApiEventMetric for PaymentMethodListResponse {} + impl ApiEventMetric for PaymentListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI)
2024-01-12T08:22:57Z
## 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 payment_id field in payment methods 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). --> ## 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 confirm false 2. call `List payment methods for a Merchant` API via postman ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d533c98b5107fb6876c11b183eb9bc382a77a2f1
juspay/hyperswitch
juspay__hyperswitch-3340
Bug: Rename `s3` feature flag to `aws_s3` Rename `s3` feature flag to `aws_s3`. This change is required so that current storage scheme becomes distinguishable, especially if in future new storage implementations like a AWS S3 alternative is integrated.
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 8897fdac2c2..88272033fb0 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,12 +10,12 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] -s3 = ["dep:aws-sdk-s3", "dep:aws-config"] +aws_s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config", "olap"] frm = [] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] +release = ["kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3d93c2f188b..b674c503542 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -88,7 +88,7 @@ pub struct Settings { pub api_keys: ApiKeys, #[cfg(feature = "kms")] pub kms: kms::KmsConfig, - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] pub file_upload_config: FileUploadConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, @@ -716,7 +716,7 @@ pub struct ApiKeys { pub expiry_reminder_days: Vec<u8>, } -#[cfg(feature = "s3")] +#[cfg(feature = "aws_s3")] #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct FileUploadConfig { @@ -848,7 +848,7 @@ impl Settings { self.kms .validate() .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] self.file_upload_config.validate()?; self.lock_settings.validate()?; self.events.validate()?; diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 569262d0d21..0b286ece843 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -127,7 +127,7 @@ impl super::settings::DrainerSettings { } } -#[cfg(feature = "s3")] +#[cfg(feature = "aws_s3")] impl super::settings::FileUploadConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index 13c4d3dfdf3..f3e56489806 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -1,8 +1,8 @@ pub mod helpers; -#[cfg(feature = "s3")] +#[cfg(feature = "aws_s3")] pub mod s3_utils; -#[cfg(not(feature = "s3"))] +#[cfg(not(feature = "aws_s3"))] pub mod fs_utils; use api_models::files; @@ -29,9 +29,9 @@ pub async fn files_create_core( ) .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] let file_key = format!("{}/{}", merchant_account.merchant_id, file_id); - #[cfg(not(feature = "s3"))] + #[cfg(not(feature = "aws_s3"))] let file_key = format!("{}_{}", merchant_account.merchant_id, file_id); let file_new = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 818067207f4..9205d42aeee 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -31,33 +31,33 @@ pub async fn get_file_purpose(field: &mut Field) -> Option<api::FilePurpose> { } pub async fn upload_file( - #[cfg(feature = "s3")] state: &AppState, + #[cfg(feature = "aws_s3")] state: &AppState, file_key: String, file: Vec<u8>, ) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] return files::s3_utils::upload_file_to_s3(state, file_key, file).await; - #[cfg(not(feature = "s3"))] + #[cfg(not(feature = "aws_s3"))] return files::fs_utils::save_file_to_fs(file_key, file); } pub async fn delete_file( - #[cfg(feature = "s3")] state: &AppState, + #[cfg(feature = "aws_s3")] state: &AppState, file_key: String, ) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] return files::s3_utils::delete_file_from_s3(state, file_key).await; - #[cfg(not(feature = "s3"))] + #[cfg(not(feature = "aws_s3"))] return files::fs_utils::delete_file_from_fs(file_key); } pub async fn retrieve_file( - #[cfg(feature = "s3")] state: &AppState, + #[cfg(feature = "aws_s3")] state: &AppState, file_key: String, ) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] return files::s3_utils::retrieve_file_from_s3(state, file_key).await; - #[cfg(not(feature = "s3"))] + #[cfg(not(feature = "aws_s3"))] return files::fs_utils::retrieve_file_from_fs(file_key); } @@ -134,7 +134,7 @@ pub async fn delete_file_using_file_id( match provider { diesel_models::enums::FileUploadProvider::Router => { delete_file( - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] state, provider_file_id, ) @@ -235,7 +235,7 @@ pub async fn retrieve_file_and_provider_file_id_from_file_id( diesel_models::enums::FileUploadProvider::Router => Ok(( Some( retrieve_file( - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] state, provider_file_id.clone(), ) @@ -365,7 +365,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( )) } else { upload_file( - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] state, file_key.clone(), create_file_request.file.clone(),
2024-01-12T11:03:29Z
## 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 renames s3 feature flag to aws_s3 so that current storage scheme is distinguishable, especially if in future new storage implementations like a AWS S3 alternative is integrated. ### 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 a rename of feature flag, so basic sanity testing should work ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
eb2a61d8597995838f21b8233653c691118b2191
juspay/hyperswitch
juspay__hyperswitch-3327
Bug: feat: Add user flow for non-email usecase If a user (merchant) does not have email service enabled, then the current invite user flow does not work. ## Feature Requirement For a merchant with no email service enabled (feature flag), have a add user flow. In this flow, the merchant is asked for a email id and password. A user will be created with this new email ID and password and he will be able to log in.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 07909a35782..f5af31c8e7f 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -86,6 +86,7 @@ pub struct InviteUserRequest { #[derive(Debug, serde::Serialize)] pub struct InviteUserResponse { pub is_email_sent: bool, + pub password: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 532f8208ecf..b1a582cedec 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,7 +1,5 @@ use api_models::user as user_api; -#[cfg(feature = "email")] -use diesel_models::user_role::UserRoleNew; -use diesel_models::{enums::UserStatus, user as storage_user}; +use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew}; #[cfg(feature = "email")] use error_stack::IntoReport; use error_stack::ResultExt; @@ -342,7 +340,6 @@ pub async fn reset_password( Ok(ApplicationResponse::StatusOk) } -#[cfg(feature = "email")] pub async fn invite_user( state: AppState, request: user_api::InviteUserRequest, @@ -395,6 +392,7 @@ pub async fn invite_user( Ok(ApplicationResponse::Json(user_api::InviteUserResponse { is_email_sent: false, + password: None, })) } else if invitee_user .as_ref() @@ -432,25 +430,37 @@ pub async fn invite_user( } })?; - let email_contents = email_types::InviteUser { - recipient_email: invitee_email, - user_name: domain::UserName::new(new_user.get_name())?, - settings: state.conf.clone(), - subject: "You have been invited to join Hyperswitch Community!", - }; - - let send_email_result = state - .email_client - .compose_and_send_email( - Box::new(email_contents), - state.conf.proxy.https_url.as_ref(), - ) - .await; - - logger::info!(?send_email_result); + let is_email_sent; + #[cfg(feature = "email")] + { + let email_contents = email_types::InviteUser { + recipient_email: invitee_email, + user_name: domain::UserName::new(new_user.get_name())?, + settings: state.conf.clone(), + subject: "You have been invited to join Hyperswitch Community!", + }; + let send_email_result = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await; + logger::info!(?send_email_result); + is_email_sent = send_email_result.is_ok(); + } + #[cfg(not(feature = "email"))] + { + is_email_sent = false; + } Ok(ApplicationResponse::Json(user_api::InviteUserResponse { - is_email_sent: send_email_result.is_ok(), + is_email_sent, + password: if cfg!(not(feature = "email")) { + Some(new_user.get_password().get_secret()) + } else { + None + }, })) } else { Err(UserErrors::InternalServerError.into()) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6625a206be2..015e3305de1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -879,6 +879,7 @@ impl User { .service(web::resource("/user/update_role").route(web::post().to(update_user_role))) .service(web::resource("/role/list").route(web::get().to(list_roles))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) + .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service( web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) @@ -901,7 +902,6 @@ impl User { ) .service(web::resource("/forgot_password").route(web::post().to(forgot_password))) .service(web::resource("/reset_password").route(web::post().to(reset_password))) - .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service( web::resource("/signup_with_merchant_id") .route(web::post().to(user_signup_with_merchant_id)), diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 7f0f0db3b69..a77b82c550e 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -333,7 +333,6 @@ pub async fn reset_password( .await } -#[cfg(feature = "email")] pub async fn invite_user( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8f204814ec4..d271ed5e29d 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -489,6 +489,10 @@ impl NewUser { self.new_merchant.clone() } + pub fn get_password(&self) -> UserPassword { + self.password.clone() + } + pub async fn insert_user_in_db( &self, db: &dyn StorageInterface, @@ -683,8 +687,7 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.0.email.clone().try_into()?; let name = UserName::new(value.0.name.clone())?; - let password = password::generate_password_hash(uuid::Uuid::new_v4().to_string().into())?; - let password = UserPassword::new(password)?; + let password = UserPassword::new(uuid::Uuid::new_v4().to_string().into())?; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self {
2024-01-11T10:13:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Enabled invite api to work without "email" feature flag <!-- 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 allows user to use user management without email feature flag. <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? ``` curl --location --request POST '<URL>/user/user/invite' \ --header 'Authorization: Bearer <JWT>' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "name": "name", "role_id": "valid_role_id" }' ``` Expected Response: with email flag ``` { "is_email_sent": true, "password": null } ``` without email flag ``` { "is_email_sent": false, "password": "some_password" } ``` <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9eaebe8db3d83105ef1e8fc784241e1fb795dd22
juspay/hyperswitch
juspay__hyperswitch-3342
Bug: [FEATURE] [Bankofamerica] Add 3DS flow for cards ### Feature Description Add 3DS flow for cards for connector BankOfAmerica. ### Possible Implementation Add 3DS flow for cards for connector BankOfAmerica. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index e20f9c1b65d..d4e11964192 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -351,6 +351,7 @@ stripe = { payment_method = "bank_transfer" } nuvei = { payment_method = "card" } shift4 = { payment_method = "card" } bluesnap = { payment_method = "card" } +bankofamerica = {payment_method = "card"} cybersource = {payment_method = "card"} nmi = {payment_method = "card"} diff --git a/config/development.toml b/config/development.toml index 5732d5f0d1d..91269005a0f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -428,6 +428,7 @@ stripe = {payment_method = "bank_transfer"} nuvei = {payment_method = "card"} shift4 = {payment_method = "card"} bluesnap = {payment_method = "card"} +bankofamerica = {payment_method = "card"} cybersource = {payment_method = "card"} nmi = {payment_method = "card"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c6934a64671..450fe106a31 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -241,6 +241,7 @@ stripe = {payment_method = "bank_transfer"} nuvei = {payment_method = "card"} shift4 = {payment_method = "card"} bluesnap = {payment_method = "card"} +bankofamerica = {payment_method = "card"} cybersource = {payment_method = "card"} nmi = {payment_method = "card"} diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index aeb3dafcfa2..0d901b99078 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -12,6 +12,7 @@ use time::OffsetDateTime; use transformers as bankofamerica; use url::Url; +use super::utils::{PaymentsAuthorizeRequestData, RouterData}; use crate::{ configs::settings, connector::{utils as connector_utils, utils::RefundsRequestData}, @@ -48,6 +49,8 @@ impl api::Refund for Bankofamerica {} impl api::RefundExecute for Bankofamerica {} impl api::RefundSync for Bankofamerica {} impl api::PaymentToken for Bankofamerica {} +impl api::PaymentsPreProcessing for Bankofamerica {} +impl api::PaymentsCompleteAuthorize for Bankofamerica {} impl Bankofamerica { pub fn generate_digest(&self, payload: &[u8]) -> String { @@ -299,6 +302,113 @@ impl } } +impl + ConnectorIntegration< + api::PreProcessing, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + > for Bankofamerica +{ + fn get_headers( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let redirect_response = req.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => Ok(format!( + "{}risk/v1/authentications", + self.base_url(connectors) + )), + Some(_) | None => Ok(format!( + "{}risk/v1/authentication-results", + self.base_url(connectors) + )), + } + } + fn get_request_body( + &self, + req: &types::PaymentsPreProcessingRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = bankofamerica::BankOfAmericaRouterData::try_from(( + &self.get_currency_unit(), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + req.request + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })?, + req, + ))?; + let connector_req = + bankofamerica::BankOfAmericaPreProcessingRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPreProcessingType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPreProcessingType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsPreProcessingRouterData, + res: Response, + ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: bankofamerica::BankOfAmericaPreProcessingResponse = res + .response + .parse_struct("BankOfAmerica AuthEnrollmentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Bankofamerica { @@ -316,13 +426,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}pts/v2/payments/", - api::ConnectorCommon::base_url(self, connectors) - )) + if req.is_three_ds() && req.request.is_card() { + Ok(format!( + "{}risk/v1/authentication-setups", + self.base_url(connectors) + )) + } else { + Ok(format!("{}pts/v2/payments/", self.base_url(connectors))) + } } fn get_request_body( @@ -336,9 +450,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.amount, req, ))?; - let connector_req = - bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + if req.is_three_ds() && req.request.is_card() { + let connector_req = + bankofamerica::BankOfAmericaAuthSetupRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } else { + let connector_req = + bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } } fn build_request( @@ -368,6 +488,130 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + if data.is_three_ds() && data.request.is_card() { + let response: bankofamerica::BankOfAmericaAuthSetupResponse = res + .response + .parse_struct("Bankofamerica AuthSetupResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } else { + let response: bankofamerica::BankOfAmericaPaymentsResponse = res + .response + .parse_struct("Bankofamerica PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } + + fn get_5xx_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: bankofamerica::BankOfAmericaServerErrorResponse = res + .response + .parse_struct("BankOfAmericaServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + }) + } +} + +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Bankofamerica +{ + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}pts/v2/payments/", self.base_url(connectors))) + } + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = bankofamerica::BankOfAmericaRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = + bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaPaymentsResponse = res .response .parse_struct("BankOfAmerica PaymentResponse") diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 6abe1b634df..72e3de0bf77 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1,6 +1,7 @@ use api_models::payments; use base64::Engine; -use common_utils::pii; +use common_utils::{ext_traits::ValueExt, pii}; +use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -8,10 +9,12 @@ use serde_json::Value; use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, CardIssuer, - PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData, + PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + PaymentsPreProcessingData, PaymentsSyncRequestData, RouterData, }, consts, core::errors, + services, types::{ self, api::{self, enums as api_enums}, @@ -85,14 +88,17 @@ pub struct BankOfAmericaPaymentsRequest { order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] + consumer_authentication_information: Option<BankOfAmericaConsumerAuthInformation>, + #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingInformation { - capture: bool, + capture: Option<bool>, payment_solution: Option<String>, + commerce_indicator: String, } #[derive(Debug, Serialize)] @@ -102,6 +108,17 @@ pub struct MerchantDefinedInformation { value: String, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformation { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + directory_server_transaction_id: Option<String>, + specification_version: Option<String>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CaptureOptions { @@ -287,6 +304,28 @@ impl } } +impl + From<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + )> for OrderInformationWithBill +{ + fn from( + (item, bill_to): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + ), + ) -> Self { + Self { + amount_details: Amount { + total_amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + }, + bill_to, + } + } +} + impl From<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -300,11 +339,40 @@ impl ), ) -> Self { Self { - capture: matches!( + capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None - ), + )), payment_solution: solution.map(String::from), + commerce_indicator: String::from("internet"), + } + } +} + +impl + From<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &BankOfAmericaConsumerAuthValidateResponse, + )> for ProcessingInformation +{ + fn from( + (item, solution, three_ds_data): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &BankOfAmericaConsumerAuthValidateResponse, + ), + ) -> Self { + Self { + capture: Some(matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + )), + payment_solution: solution.map(String::from), + commerce_indicator: three_ds_data + .indicator + .to_owned() + .unwrap_or(String::from("internet")), } } } @@ -319,6 +387,16 @@ impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } +impl From<&BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for ClientReferenceInformation +{ + fn from(item: &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>) -> Self { + Self { + code: Some(item.router_data.connector_request_reference_id.clone()), + } + } +} + impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { fn foreign_from(metadata: Value) -> Self { let hashmap: std::collections::BTreeMap<String, Value> = @@ -367,6 +445,83 @@ pub struct Avs { code_raw: String, } +impl + TryFrom<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + )> for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + + let three_ds_info: BankOfAmericaThreeDSMetadata = item + .router_data + .request + .connector_meta + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "connector_meta", + })? + .parse_value("BankOfAmericaThreeDSMetadata") + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "Merchant connector account metadata", + })?; + + let processing_information = + ProcessingInformation::from((item, None, &three_ds_info.three_ds_data)); + + let consumer_authentication_information = Some(BankOfAmericaConsumerAuthInformation { + ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator, + cavv: three_ds_info.three_ds_data.cavv, + ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data, + xid: three_ds_info.three_ds_data.xid, + directory_server_transaction_id: three_ds_info + .three_ds_data + .directory_server_transaction_id, + specification_version: three_ds_info.three_ds_data.specification_version, + }); + + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information, + merchant_defined_information, + }) + } +} + impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -410,6 +565,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -455,6 +611,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -496,6 +653,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -552,6 +710,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> order_information, merchant_defined_information, client_reference_information, + consumer_authentication_information: None, }) } } @@ -608,6 +767,64 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthSetupRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> + for BankOfAmericaAuthSetupRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + Ok(Self { + payment_information, + client_reference_information, + }) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + ) + .into()) + } + } + } +} + #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BankofamericaPaymentStatus { @@ -669,6 +886,29 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus { } } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationResponse { + access_token: String, + device_data_collection_url: String, + reference_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthSetupInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum BankOfAmericaAuthSetupResponse { + ClientAuthSetupInfo(ClientAuthSetupInfoResponse), + ErrorInformation(BankOfAmericaErrorInformationResponse), +} + #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum BankOfAmericaPaymentsResponse { @@ -799,6 +1039,494 @@ fn get_payment_response( } } +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: Some(services::RedirectForm::CybersourceAuthSetup { + access_token: info_response + .consumer_authentication_information + .access_token, + ddc_url: info_response + .consumer_authentication_information + .device_data_collection_url, + reference_id: info_response + .consumer_authentication_information + .reference_id, + }), + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + }), + ..item.data + }), + BankOfAmericaAuthSetupResponse::ErrorInformation(error_response) => { + let error_reason = error_response + .error_information + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason; + Ok(Self { + response: Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }), + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationRequest { + return_url: String, + reference_id: String, +} +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthEnrollmentRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationRequest, + order_information: OrderInformationWithBill, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub struct BankOfAmericaRedirectionAuthResponse { + pub transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationValidateRequest { + authentication_transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthValidateRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationValidateRequest, + order_information: OrderInformation, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum BankOfAmericaPreProcessingRequest { + AuthEnrollment(BankOfAmericaAuthEnrollmentRequest), + AuthValidate(BankOfAmericaAuthValidateRequest), +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsPreProcessingRouterData>> + for BankOfAmericaPreProcessingRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsPreProcessingRouterData>, + ) -> Result<Self, Self::Error> { + let client_reference_information = ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }; + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "payment_method_data", + }, + )?; + let payment_information = match payment_method_data { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + Ok(PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + })) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + )) + } + }?; + + let redirect_response = item.router_data.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + + let amount_details = Amount { + total_amount: item.amount.clone(), + currency: item.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + }, + )?, + }; + + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => { + let reference_id = param + .clone() + .peek() + .split_once('=') + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.params.reference_id", + })? + .1 + .to_string(); + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill { + amount_details, + bill_to, + }; + Ok(Self::AuthEnrollment(BankOfAmericaAuthEnrollmentRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + BankOfAmericaConsumerAuthInformationRequest { + return_url: item.router_data.request.get_complete_authorize_url()?, + reference_id, + }, + order_information, + })) + } + Some(_) | None => { + let redirect_payload: BankOfAmericaRedirectionAuthResponse = redirect_response + .payload + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.payload", + })? + .peek() + .clone() + .parse_value("BankOfAmericaRedirectionAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let order_information = OrderInformation { amount_details }; + Ok(Self::AuthValidate(BankOfAmericaAuthValidateRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + BankOfAmericaConsumerAuthInformationValidateRequest { + authentication_transaction_id: redirect_payload.transaction_id, + }, + order_information, + })) + } + } + } +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_data", + }, + )?; + match payment_method_data { + payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + ) + .into()) + } + } + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum BankOfAmericaAuthEnrollmentStatus { + PendingAuthentication, + AuthenticationSuccessful, + AuthenticationFailed, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthValidateResponse { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + specification_version: Option<String>, + directory_server_transaction_id: Option<String>, + indicator: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct BankOfAmericaThreeDSMetadata { + three_ds_data: BankOfAmericaConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse { + access_token: Option<String>, + step_up_url: Option<String>, + //Added to segregate the three_ds_data in a separate struct + #[serde(flatten)] + validate_response: BankOfAmericaConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthCheckInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationEnrollmentResponse, + status: BankOfAmericaAuthEnrollmentStatus, + error_information: Option<BankOfAmericaErrorInformation>, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum BankOfAmericaPreProcessingResponse { + ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), + ErrorInformation(BankOfAmericaErrorInformationResponse), +} + +impl From<BankOfAmericaAuthEnrollmentStatus> for enums::AttemptStatus { + fn from(item: BankOfAmericaAuthEnrollmentStatus) -> Self { + match item { + BankOfAmericaAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, + BankOfAmericaAuthEnrollmentStatus::AuthenticationSuccessful => { + Self::AuthenticationSuccessful + } + BankOfAmericaAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaPreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaPreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaPreProcessingResponse::ClientAuthCheckInfo(info_response) => { + let status = enums::AttemptStatus::from(info_response.status); + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + let response = Err(types::ErrorResponse::from(( + &info_response.error_information, + &risk_info, + item.http_code, + info_response.id.clone(), + ))); + + Ok(Self { + status, + response, + ..item.data + }) + } else { + let connector_response_reference_id = Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ); + + let redirection_data = match ( + info_response + .consumer_authentication_information + .access_token, + info_response + .consumer_authentication_information + .step_up_url, + ) { + (Some(access_token), Some(step_up_url)) => { + Some(services::RedirectForm::CybersourceConsumerAuth { + access_token, + step_up_url, + }) + } + _ => None, + }; + let three_ds_data = serde_json::to_value( + info_response + .consumer_authentication_information + .validate_response, + ) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data, + mandate_reference: None, + connector_metadata: Some( + serde_json::json!({"three_ds_data":three_ds_data}), + ), + network_txn_id: None, + connector_response_reference_id, + incremental_authorization_allowed: None, + }), + ..item.data + }) + } + } + BankOfAmericaPreProcessingResponse::ErrorInformation(ref error_response) => { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + Ok(Self { + response, + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = enums::AttemptStatus::foreign_from(( + info_response.status.clone(), + item.data.request.is_auto_capture()?, + )); + let response = get_payment_response((&info_response, status, item.http_code)); + Ok(Self { + status, + response, + ..item.data + }) + } + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))) + } + } + } +} + impl<F> TryFrom< types::ResponseRouterData< diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 69159c10c8a..b300e97b44a 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -874,6 +874,33 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } + + fn get_5xx_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: cybersource::CybersourceServerErrorResponse = res + .response + .parse_struct("CybersourceServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(types::ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + }) + } } impl diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 21cdec92ccb..49a9bcf6664 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1489,7 +1489,8 @@ where router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) - } else if connector.connector_name == router_types::Connector::Cybersource + } else if (connector.connector_name == router_types::Connector::Cybersource + || connector.connector_name == router_types::Connector::Bankofamerica) && is_operation_complete_authorize(&operation) && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs { diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 6dd692f1525..c9f9d6d87f5 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -147,7 +147,6 @@ impl<const T: u8> default_imp_for_complete_authorize!( connector::Aci, connector::Adyen, - connector::Bankofamerica, connector::Bitpay, connector::Boku, connector::Cashtocode, @@ -863,7 +862,6 @@ default_imp_for_pre_processing_steps!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, - connector::Bankofamerica, connector::Bitpay, connector::Bluesnap, connector::Boku,
2024-01-12T11:58:44Z
## 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 --> Implement 3DS flow for cards ``` Legend: UB: User Browser M: Merchant HS: Hyperswitch CS: Bankofamerica/Cybersource Connector ``` ![3DS FLOW DIAGRAM](https://github.com/juspay/hyperswitch/assets/41580413/9f2e0e71-65df-4310-84cf-1419090a680f) ### 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/3342 ## 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)? --> ### QA Testing ![Screenshot 2024-01-12 at 5 35 04 PM](https://github.com/juspay/hyperswitch/assets/41580413/bdab526f-736b-44c1-8904-3ae51e9781f6) ![Screenshot 2024-01-12 at 5 33 54 PM](https://github.com/juspay/hyperswitch/assets/41580413/55ca3a43-b8de-43f8-b463-3555a8e79e21) ![Screenshot 2024-01-12 at 5 33 10 PM](https://github.com/juspay/hyperswitch/assets/41580413/6a9d3d59-1a7d-411d-b5e3-61f59376e9c8) ![Screenshot 2024-01-12 at 5 33 28 PM](https://github.com/juspay/hyperswitch/assets/41580413/3ea39f9f-2ea1-4d25-a85e-fcb9b9522e31) - Test Non-3DS flows to confirm they are not affected - Test 3DS transactions All the possible 3DS test cases and test cards are available here: https://developer.cybersource.com/content/dam/docs/cybs/en-us/payer-authentication/developer/all/rest/payer-auth.pdf 3DS Payment Curl: `curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "340000000001098", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph", "card_cvc": "123" } }, "billing": { "address": { "line1": "sdv", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "46282", "country": "US", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "count_tickets": "1", "transaction_number": 2233 }, "business_label": "food", "business_country": "US" }'` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8678f8d1448b5ce430931bfbbc269ef979d9eea7
juspay/hyperswitch
juspay__hyperswitch-3322
Bug: fix: reset tracking id api for connector onboarding ## Problem To support the onboarding flow where merchants can signin/signup directly into the connector's website and give us the credentials of the account we had created onboarding apis (action_url and sync) which uses `tracking_id` to track the onboarding progress of a merchant. And the `tracking_id` we are using currently is `connector_id`. We are facing an issue in the connector update flow where the merchant tries the onboarding flow again to signin/signup to a new account. If they don't signup/signin and fetches the current status, the sync api will automatically give the progress of the previous account they have signed in in the create flow. ## Possible solution Instead of using the `connector_id` as the `tracking_id`, we will be use `connector_id_timestamp` as the `tracking_id`. We will create a reset tracking id api which will reset the `tracking_id` by changing the timestamp suffix of the current `tracking_id`. This will be called before the merchant tries to update the mca. As the `tracking_id` is changed in create and update flow, we will no longer get the details of the account which is used in the create flow.
diff --git a/crates/api_models/src/connector_onboarding.rs b/crates/api_models/src/connector_onboarding.rs index 759d3cb97f1..7e8288d9747 100644 --- a/crates/api_models/src/connector_onboarding.rs +++ b/crates/api_models/src/connector_onboarding.rs @@ -52,3 +52,9 @@ pub struct PayPalOnboardingDone { pub struct PayPalIntegrationDone { pub connector_id: String, } + +#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] +pub struct ResetTrackingIdRequest { + pub connector_id: String, + pub connector: enums::Connector, +} diff --git a/crates/api_models/src/events/connector_onboarding.rs b/crates/api_models/src/events/connector_onboarding.rs index 998dc384d62..0da89f61da7 100644 --- a/crates/api_models/src/events/connector_onboarding.rs +++ b/crates/api_models/src/events/connector_onboarding.rs @@ -2,11 +2,13 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::connector_onboarding::{ ActionUrlRequest, ActionUrlResponse, OnboardingStatus, OnboardingSyncRequest, + ResetTrackingIdRequest, }; common_utils::impl_misc_api_event_type!( ActionUrlRequest, ActionUrlResponse, OnboardingSyncRequest, - OnboardingStatus + OnboardingStatus, + ResetTrackingIdRequest ); diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index afe76184630..7b8d6fa0827 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -74,6 +74,9 @@ pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant"; +#[cfg(feature = "olap")] +pub const CONNECTOR_ONBOARDING_CONFIG_PREFIX: &str = "onboarding"; + /// Max payment session expiry pub const MAX_SESSION_EXPIRY: u32 = 7890000; diff --git a/crates/router/src/core/connector_onboarding.rs b/crates/router/src/core/connector_onboarding.rs index e48026edc2d..e6c1fc9d378 100644 --- a/crates/router/src/core/connector_onboarding.rs +++ b/crates/router/src/core/connector_onboarding.rs @@ -1,5 +1,4 @@ use api_models::{connector_onboarding as api, enums}; -use error_stack::ResultExt; use masking::Secret; use crate::{ @@ -19,16 +18,23 @@ pub trait AccessToken { pub async fn get_action_url( state: AppState, + user_from_token: auth::UserFromToken, request: api::ActionUrlRequest, ) -> RouterResponse<api::ActionUrlResponse> { + utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) + .await?; + let connector_onboarding_conf = state.conf.connector_onboarding.clone(); let is_enabled = utils::is_enabled(request.connector, &connector_onboarding_conf); + let tracking_id = + utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector) + .await?; match (is_enabled, request.connector) { (Some(true), enums::Connector::Paypal) => { let action_url = Box::pin(paypal::get_action_url_from_paypal( state, - request.connector_id, + tracking_id, request.return_url, )) .await?; @@ -49,40 +55,42 @@ pub async fn sync_onboarding_status( user_from_token: auth::UserFromToken, request: api::OnboardingSyncRequest, ) -> RouterResponse<api::OnboardingStatus> { - let merchant_account = user_from_token - .get_merchant_account(state.clone()) - .await - .change_context(ApiErrorResponse::MerchantAccountNotFound)?; + utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) + .await?; + let connector_onboarding_conf = state.conf.connector_onboarding.clone(); let is_enabled = utils::is_enabled(request.connector, &connector_onboarding_conf); + let tracking_id = + utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector) + .await?; match (is_enabled, request.connector) { (Some(true), enums::Connector::Paypal) => { let status = Box::pin(paypal::sync_merchant_onboarding_status( state.clone(), - request.connector_id.clone(), + tracking_id, )) .await?; if let api::OnboardingStatus::PayPal(api::PayPalOnboardingStatus::Success( - ref inner_data, + ref paypal_onboarding_data, )) = status { let connector_onboarding_conf = state.conf.connector_onboarding.clone(); let auth_details = oss_types::ConnectorAuthType::SignatureKey { api_key: connector_onboarding_conf.paypal.client_secret, key1: connector_onboarding_conf.paypal.client_id, - api_secret: Secret::new(inner_data.payer_id.clone()), + api_secret: Secret::new(paypal_onboarding_data.payer_id.clone()), }; - let some_data = paypal::update_mca( + let update_mca_data = paypal::update_mca( &state, - &merchant_account, + user_from_token.merchant_id, request.connector_id.to_owned(), auth_details, ) .await?; return Ok(ApplicationResponse::Json(api::OnboardingStatus::PayPal( - api::PayPalOnboardingStatus::ConnectorIntegrated(some_data), + api::PayPalOnboardingStatus::ConnectorIntegrated(update_mca_data), ))); } Ok(ApplicationResponse::Json(status)) @@ -94,3 +102,15 @@ pub async fn sync_onboarding_status( .into()), } } + +pub async fn reset_tracking_id( + state: AppState, + user_from_token: auth::UserFromToken, + request: api::ResetTrackingIdRequest, +) -> RouterResponse<()> { + utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) + .await?; + utils::set_tracking_id_in_configs(&state, &request.connector_id, request.connector).await?; + + Ok(ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs index 30aa69067b5..f18681f8cfd 100644 --- a/crates/router/src/core/connector_onboarding/paypal.rs +++ b/crates/router/src/core/connector_onboarding/paypal.rs @@ -23,11 +23,11 @@ fn build_referral_url(state: AppState) -> String { async fn build_referral_request( state: AppState, - connector_id: String, + tracking_id: String, return_url: String, ) -> RouterResult<Request> { let access_token = utils::paypal::generate_access_token(state.clone()).await?; - let request_body = types::paypal::PartnerReferralRequest::new(connector_id, return_url); + let request_body = types::paypal::PartnerReferralRequest::new(tracking_id, return_url); utils::paypal::build_paypal_post_request( build_referral_url(state), @@ -38,12 +38,12 @@ async fn build_referral_request( pub async fn get_action_url_from_paypal( state: AppState, - connector_id: String, + tracking_id: String, return_url: String, ) -> RouterResult<String> { let referral_request = Box::pin(build_referral_request( state.clone(), - connector_id, + tracking_id, return_url, )) .await?; @@ -137,7 +137,7 @@ async fn find_paypal_merchant_by_tracking_id( pub async fn update_mca( state: &AppState, - merchant_account: &oss_types::domain::MerchantAccount, + merchant_id: String, connector_id: String, auth_details: oss_types::ConnectorAuthType, ) -> RouterResult<oss_api_types::MerchantConnectorResponse> { @@ -159,13 +159,9 @@ pub async fn update_mca( connector_webhook_details: None, pm_auth_config: None, }; - let mca_response = admin::update_payment_connector( - state.clone(), - &merchant_account.merchant_id, - &connector_id, - request, - ) - .await?; + let mca_response = + admin::update_payment_connector(state.clone(), &merchant_id, &connector_id, request) + .await?; match mca_response { ApplicationResponse::Json(mca_data) => Ok(mca_data), diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6625a206be2..03e63553a66 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -942,5 +942,6 @@ impl ConnectorOnboarding { .app_data(web::Data::new(state)) .service(web::resource("/action_url").route(web::post().to(get_action_url))) .service(web::resource("/sync").route(web::post().to(sync_onboarding_status))) + .service(web::resource("/reset_tracking_id").route(web::post().to(reset_tracking_id))) } } diff --git a/crates/router/src/routes/connector_onboarding.rs b/crates/router/src/routes/connector_onboarding.rs index b7c39b3c1d2..f5555f5bf9b 100644 --- a/crates/router/src/routes/connector_onboarding.rs +++ b/crates/router/src/routes/connector_onboarding.rs @@ -20,7 +20,7 @@ pub async fn get_action_url( state, &http_req, req_payload.clone(), - |state, _: auth::UserFromToken, req| core::get_action_url(state, req), + core::get_action_url, &auth::JWTAuth(Permission::MerchantAccountWrite), api_locking::LockAction::NotApplicable, )) @@ -45,3 +45,22 @@ pub async fn sync_onboarding_status( )) .await } + +pub async fn reset_tracking_id( + state: web::Data<AppState>, + http_req: HttpRequest, + json_payload: web::Json<api_types::ResetTrackingIdRequest>, +) -> HttpResponse { + let flow = Flow::ResetTrackingId; + let req_payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow.clone(), + state, + &http_req, + req_payload.clone(), + core::reset_tracking_id, + &auth::JWTAuth(Permission::MerchantAccountWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 10f408f3d4f..65d65366013 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -178,7 +178,9 @@ impl From<Flow> for ApiIdentifier { Self::UserRole } - Flow::GetActionUrl | Flow::SyncOnboardingStatus => Self::ConnectorOnboarding, + Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { + Self::ConnectorOnboarding + } } } } diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rs index e8afcd68a46..03735e61cc7 100644 --- a/crates/router/src/utils/connector_onboarding.rs +++ b/crates/router/src/utils/connector_onboarding.rs @@ -1,6 +1,11 @@ +use diesel_models::{ConfigNew, ConfigUpdate}; +use error_stack::ResultExt; + +use super::errors::StorageErrorExt; use crate::{ + consts, core::errors::{api_error_response::NotImplementedMessage, ApiErrorResponse, RouterResult}, - routes::app::settings, + routes::{app::settings, AppState}, types::{self, api::enums}, }; @@ -34,3 +39,105 @@ pub fn is_enabled( _ => None, } } + +pub async fn check_if_connector_exists( + state: &AppState, + connector_id: &str, + merchant_id: &str, +) -> RouterResult<()> { + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; + + let _connector = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + merchant_id, + connector_id, + &key_store, + ) + .await + .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound { + id: connector_id.to_string(), + })?; + + Ok(()) +} + +pub async fn set_tracking_id_in_configs( + state: &AppState, + connector_id: &str, + connector: enums::Connector, +) -> RouterResult<()> { + let timestamp = common_utils::date_time::now_unix_timestamp().to_string(); + let find_config = state + .store + .find_config_by_key(&build_key(connector_id, connector)) + .await; + + if find_config.is_ok() { + state + .store + .update_config_by_key( + &build_key(connector_id, connector), + ConfigUpdate::Update { + config: Some(timestamp), + }, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Error updating data in configs table")?; + } else if find_config + .as_ref() + .map_err(|e| e.current_context().is_db_not_found()) + .err() + .unwrap_or(false) + { + state + .store + .insert_config(ConfigNew { + key: build_key(connector_id, connector), + config: timestamp, + }) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Error inserting data in configs table")?; + } else { + find_config.change_context(ApiErrorResponse::InternalServerError)?; + } + + Ok(()) +} + +pub async fn get_tracking_id_from_configs( + state: &AppState, + connector_id: &str, + connector: enums::Connector, +) -> RouterResult<String> { + let timestamp = state + .store + .find_config_by_key_unwrap_or( + &build_key(connector_id, connector), + Some(common_utils::date_time::now_unix_timestamp().to_string()), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Error getting data from configs table")? + .config; + + Ok(format!("{}_{}", connector_id, timestamp)) +} + +fn build_key(connector_id: &str, connector: enums::Connector) -> String { + format!( + "{}_{}_{}", + consts::CONNECTOR_ONBOARDING_CONFIG_PREFIX, + connector, + connector_id, + ) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index e37e15443bd..110402444c5 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -311,6 +311,8 @@ pub enum Flow { GetActionUrl, /// Sync connector onboarding status SyncOnboardingStatus, + /// Reset tracking id + ResetTrackingId, /// Verify email Token VerifyEmail, /// Send verify email
2024-01-03T08:48:26Z
## 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 --> 1. This PR adds checks in connector_onboarding to only proceed if the connector exists for the given merchant_account. 2. Reset tracking id api has been added to connector onboarding, which will reset the tracking details of the onboarded merchant. This can be used to update the process without any interference of previous account. ### 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` 3. `crates/router/src/configs` 4. `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). --> 1. To catch any errors without the connector id check beforehand. 2. To make the update flow of connector onboarding better. ## 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)? --> Postman. ``` curl --location 'http://localhost:8080/connector_onboarding/action_url' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "connector": "paypal", "connector_id": "", "return_url": "https://google.com" }' ``` ``` curl --location 'http://localhost:8080/connector_onboarding/sync' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "connector": "paypal", "profile_id": "", "connector_id": "" }' ``` If the connector_id is invalid, these apis will throw this error ``` { "error": { "type": "invalid_request", "message": "Merchant connector account does not exist in our records", "code": "HE_02", "reason": " does not exist" } } ``` This api will reset the progress of the onboarding flow. This api will give 200 OK if everything works correctly. ``` curl --location 'http://localhost:8080/connector_onboarding/reset_tracking_id' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "connector_id": "", "connector": "paypal" }' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5a1a3da7502ce9e13546b896477d82719162d5b6
juspay/hyperswitch
juspay__hyperswitch-3316
Bug: [REFACTOR] : [Bluesnap] Add connector_transaction_id as fallback for webhooks ### Bug Description Currently we are only consuming `merchant_transaction_id` from the webhook body, this was done to tackle the timeouts issue, but seems like Bluesnap doesn't always includes this id, so we need to add `connector_transaction_id` as fallback for webhook body ### Expected Behavior add `connector_transaction_id` as fallback for webhook body, so that even if merchant_transaction_id is not present webhook can be processed ### Actual Behavior Currently we are only consuming `merchant_transaction_id` from the webhook body, this was done to tackle the timeouts issue, but seems like Bluesnap doesn't always includes this id, so we need to add `connector_transaction_id` as fallback for webhook body ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index edcad00c983..e54d8320d0f 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -1043,11 +1043,19 @@ impl api::IncomingWebhook for Bluesnap { | bluesnap::BluesnapWebhookEvents::Charge | bluesnap::BluesnapWebhookEvents::Chargeback | bluesnap::BluesnapWebhookEvents::ChargebackStatusChanged => { - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::PaymentAttemptId( - webhook_body.merchant_transaction_id, - ), - )) + if webhook_body.merchant_transaction_id.is_empty() { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + webhook_body.reference_number, + ), + )) + } else { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::PaymentAttemptId( + webhook_body.merchant_transaction_id, + ), + )) + } } bluesnap::BluesnapWebhookEvents::Refund => { Ok(api_models::webhooks::ObjectReferenceId::RefundId(
2024-01-10T13:44:27Z
## 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 --> add connector_txn_id fallback for webhook ### 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). --> #3316 ## 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)? --> Trigger webhooks from Bluesnap with and without `merchant_transaction_id` and receive outgoing webhooks from Hyperswitch <img width="1424" alt="Screenshot 2024-01-10 at 7 13 24 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/5a743336-f53a-421f-9d23-d0e75344232d"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e0e28b87c0647252918ef110cd7614c46b5cf943
juspay/hyperswitch
juspay__hyperswitch-3320
Bug: audit trail - add connector events ### Connector Events Audit trail Build a connector events audit trail endpoint for fetching all events from `connector_events_audit` table for ops audit trail. ![Image](https://github.com/juspay/hyperswitch/assets/21202349/3ae37c76-117e-46af-8e5c-3c9b74410efa) can refer to the existing API Events audit trail implementation [here](https://github.com/juspay/hyperswitch/blob/main/crates/analytics/src/api_event/events.rs) ``` curl --location 'https://sandbox.hyperswitch.io/analytics/v1/api_event_logs?type=Payment&payment_id=pay_yEsFwSqi6Umv8LVGFFPD' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjBmZDAyNzAtNTE1MS00MWVhLWJiMWItMGY0ZWExZGNmYjQzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjg5OTI0ODQzIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNzA0ODgyODg5LCJvcmdfaWQiOiJvcmdfRk5ZWjhQaE5CQjdtV1hodWxWQW0ifQ.LCgIW8uMGVo2WRFt2irzQ1D8sHuRBSbeRkTGt1qxsXM' ``` The API contract would involve a simple `GET analytics/v1/connector_event_logs` path. with similar response format as above curl request
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index b8fd5e6a35d..f81c29c801c 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -21,6 +21,7 @@ use crate::{ filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, + connector_events::events::ConnectorEventsResult, outgoing_webhook_event::events::OutgoingWebhookLogsResult, sdk_events::events::SdkEventsResult, types::TableEngine, @@ -121,6 +122,7 @@ impl AnalyticsDataSource for ClickhouseClient { } AnalyticsCollection::SdkEvents => TableEngine::BasicTree, AnalyticsCollection::ApiEvents => TableEngine::BasicTree, + AnalyticsCollection::ConnectorEvents => TableEngine::BasicTree, AnalyticsCollection::OutgoingWebhookEvent => TableEngine::BasicTree, } } @@ -147,6 +149,7 @@ impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} +impl super::connector_events::events::ConnectorEventLogAnalytics for ClickhouseClient {} impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics for ClickhouseClient { @@ -188,6 +191,18 @@ impl TryInto<SdkEventsResult> for serde_json::Value { } } +impl TryInto<ConnectorEventsResult> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<ConnectorEventsResult, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse ConnectorEventsResult in clickhouse results", + )) + } +} + impl TryInto<PaymentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; @@ -344,6 +359,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::SdkEvents => Ok("sdk_events_dist".to_string()), Self::ApiEvents => Ok("api_audit_log".to_string()), Self::PaymentIntent => Ok("payment_intents_dist".to_string()), + Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), } } diff --git a/crates/analytics/src/connector_events.rs b/crates/analytics/src/connector_events.rs new file mode 100644 index 00000000000..c7c31306a2c --- /dev/null +++ b/crates/analytics/src/connector_events.rs @@ -0,0 +1,5 @@ +mod core; +pub mod events; +pub trait ConnectorEventAnalytics: events::ConnectorEventLogAnalytics {} + +pub use self::core::connector_events_core; diff --git a/crates/analytics/src/connector_events/core.rs b/crates/analytics/src/connector_events/core.rs new file mode 100644 index 00000000000..15f841af5f8 --- /dev/null +++ b/crates/analytics/src/connector_events/core.rs @@ -0,0 +1,27 @@ +use api_models::analytics::connector_events::ConnectorEventsRequest; +use common_utils::errors::ReportSwitchExt; +use error_stack::{IntoReport, ResultExt}; + +use super::events::{get_connector_events, ConnectorEventsResult}; +use crate::{errors::AnalyticsResult, types::FiltersError, AnalyticsProvider}; + +pub async fn connector_events_core( + pool: &AnalyticsProvider, + req: ConnectorEventsRequest, + merchant_id: String, +) -> AnalyticsResult<Vec<ConnectorEventsResult>> { + let data = match pool { + AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented( + "Connector Events not implemented for SQLX", + )) + .into_report() + .attach_printable("SQL Analytics is not implemented for Connector Events"), + AnalyticsProvider::Clickhouse(ckh_pool) + | AnalyticsProvider::CombinedSqlx(_, ckh_pool) + | AnalyticsProvider::CombinedCkh(_, ckh_pool) => { + get_connector_events(&merchant_id, req, ckh_pool).await + } + } + .switch()?; + Ok(data) +} diff --git a/crates/analytics/src/connector_events/events.rs b/crates/analytics/src/connector_events/events.rs new file mode 100644 index 00000000000..096520777ee --- /dev/null +++ b/crates/analytics/src/connector_events/events.rs @@ -0,0 +1,63 @@ +use api_models::analytics::{ + connector_events::{ConnectorEventsRequest, QueryType}, + Granularity, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; +pub trait ConnectorEventLogAnalytics: LoadRow<ConnectorEventsResult> {} + +pub async fn get_connector_events<T>( + merchant_id: &String, + query_param: ConnectorEventsRequest, + pool: &T, +) -> FiltersResult<Vec<ConnectorEventsResult>> +where + T: AnalyticsDataSource + ConnectorEventLogAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::ConnectorEvents); + query_builder.add_select_column("*").switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + match query_param.query_param { + QueryType::Payment { payment_id } => query_builder + .add_filter_clause("payment_id", payment_id) + .switch()?, + } + //TODO!: update the execute_query function to return reports instead of plain errors... + query_builder + .execute_query::<ConnectorEventsResult, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ConnectorEventsResult { + pub merchant_id: String, + pub payment_id: String, + pub connector_name: Option<String>, + pub request_id: Option<String>, + pub flow: String, + pub request: String, + pub response: Option<String>, + pub error: Option<String>, + pub status_code: u16, + pub latency: Option<u128>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + pub method: Option<String>, +} diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 8529807a1a1..501bd58527c 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -7,6 +7,7 @@ mod query; pub mod refunds; pub mod api_event; +pub mod connector_events; pub mod outgoing_webhook_event; pub mod sdk_events; mod sqlx; diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index e32b85a5367..7ab8a2aa4bc 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -429,6 +429,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection { Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::PaymentIntent => Ok("payment_intent".to_string()), + Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("ConnectorEvents table is not implemented for Sqlx"))?, Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?, } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 8da4655e255..18e9e9f4334 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -26,6 +26,7 @@ pub enum AnalyticsCollection { SdkEvents, ApiEvents, PaymentIntent, + ConnectorEvents, OutgoingWebhookEvent, } diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index e0d3fa671b6..c6ca215f9f7 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -12,6 +12,7 @@ use self::{ pub use crate::payments::TimeRange; pub mod api_event; +pub mod connector_events; pub mod outgoing_webhook_event; pub mod payments; pub mod refunds; diff --git a/crates/api_models/src/analytics/connector_events.rs b/crates/api_models/src/analytics/connector_events.rs new file mode 100644 index 00000000000..b2974b0a339 --- /dev/null +++ b/crates/api_models/src/analytics/connector_events.rs @@ -0,0 +1,11 @@ +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(tag = "type")] +pub enum QueryType { + Payment { payment_id: String }, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct ConnectorEventsRequest { + #[serde(flatten)] + pub query_param: QueryType, +} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 26a9d222d6b..43a72b7e392 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -17,10 +17,12 @@ use common_utils::{ impl_misc_api_event_type, }; +#[allow(unused_imports)] use crate::{ admin::*, analytics::{ - api_event::*, outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, *, + api_event::*, connector_events::ConnectorEventsRequest, + outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, *, }, api_keys::*, cards_info::*, @@ -94,6 +96,7 @@ impl_misc_api_event_type!( GetApiEventMetricRequest, SdkEventsRequest, ReportRequest, + ConnectorEventsRequest, OutgoingWebhookLogsRequest ); diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index c62de5bd29a..3f0febcc592 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -3,7 +3,8 @@ pub use analytics::*; pub mod routes { use actix_web::{web, Responder, Scope}; use analytics::{ - api_event::api_events_core, errors::AnalyticsError, lambda_utils::invoke_lambda, + api_event::api_events_core, connector_events::connector_events_core, + errors::AnalyticsError, lambda_utils::invoke_lambda, outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core, }; use api_models::analytics::{ @@ -71,6 +72,10 @@ pub mod routes { ) .service(web::resource("api_event_logs").route(web::get().to(get_api_events))) .service(web::resource("sdk_event_logs").route(web::post().to(get_sdk_events))) + .service( + web::resource("connector_event_logs") + .route(web::get().to(get_connector_events)), + ) .service( web::resource("outgoing_webhook_event_logs") .route(web::get().to(get_outgoing_webhook_events)), @@ -585,4 +590,26 @@ pub mod routes { )) .await } + + pub async fn get_connector_events( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Query<api_models::analytics::connector_events::ConnectorEventsRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetConnectorEvents; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + connector_events_core(&state.pool, req, auth.merchant_account.merchant_id) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } } diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 0127d07170f..9139b5eed41 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -52,6 +52,7 @@ pub enum AnalyticsFlow { GenerateRefundReport, GetApiEventMetrics, GetApiEventFilters, + GetConnectorEvents, GetOutgoingWebhookEvents, }
2024-01-10T20:00:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description adding GET api for query to fetch connector events log by specified `payment_id` ### 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? ``` curl 'http://localhost:8080/analytics/v1/connector_event_logs?type=Payment&payment_id=pay_yfkCogrWxVbB8O0biPkh' \ -H 'Accept: */*' \ -H 'Accept-Language: en-GB,en' \ -H 'Authorization: Bearer *' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Origin: http://localhost:9000' \ -H 'Referer: http://localhost:9000/' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-site' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36' \ -H 'api-key: hyperswitch' \ -H 'sec-ch-ua: "Chromium";v="112", "Brave";v="112", "Not:A-Brand";v="99"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --compressed ``` `[{"merchant_id":"Allconnector123","payment_id":"pay_yfkCogrWxVbB8O0biPkh","connector_name":"stripe","request_id":"018cf773-0564-77e8-9e89-6870acfff2db","flow":"Authorize","request":"{\"amount\":6500,\"currency\":\"USD\",\"statement_descriptor_suffix\":null,\"statement_descriptor\":null,\"metadata[order_id]\":\"pay_yfkCogrWxVbB8O0biPkh_1\",\"metadata[is_refund_id_as_reference]\":null,\"return_url\":\"https://sandbox.hyperswitch.io/payments/pay_yfkCogrWxVbB8O0biPkh/Allconnector123/redirect/response/stripe\",\"confirm\":true,\"mandate\":null,\"payment_method\":null,\"customer\":\"*** alloc::string::String ***\",\"description\":\"Hello this is description\",\"shipping[address][city]\":\"Banglore\",\"shipping[address][country]\":\"US\",\"shipping[address][line1]\":\"*** alloc::string::String ***\",\"shipping[address][line2]\":\"*** alloc::string::String ***\",\"shipping[address][postal_code]\":\"*** alloc::string::String ***\",\"shipping[address][state]\":\"*** alloc::string::String ***\",\"shipping[name]\":\"*** alloc::string::String ***\",\"shipping[phone]\":\"*** alloc::string::String ***\",\"payment_method_data[billing_details][email]\":null,\"payment_method_data[billing_details][address][country]\":null,\"payment_method_data[billing_details][name]\":null,\"payment_method_data[billing_details][address][city]\":null,\"payment_method_data[billing_details][address][line1]\":null,\"payment_method_data[billing_details][address][line2]\":null,\"payment_method_data[billing_details][address][postal_code]\":null,\"payment_method_data[type]\":\"card\",\"payment_method_data[card][number]\":\"400000**********\",\"payment_method_data[card][exp_month]\":\"*** alloc::string::String ***\",\"payment_method_data[card][exp_year]\":\"*** alloc::string::String ***\",\"payment_method_data[card][cvc]\":\"*** alloc::string::String ***\",\"payment_method_options[card][request_three_d_secure]\":\"any\",\"capture_method\":\"automatic\",\"payment_method_options\":null,\"setup_future_usage\":null,\"off_session\":null,\"payment_method_types[0]\":\"card\"}","response":"{\\n \\\"id\\\": \\\"pi_3OXInzD5R7gDAGff1cGAxxHo\\\",\\n \\\"object\\\": \\\"payment_intent\\\",\\n \\\"amount\\\": 6500,\\n \\\"amount_capturable\\\": 0,\\n \\\"amount_details\\\": {\\n \\\"tip\\\": {}\\n },\\n \\\"amount_received\\\": 0,\\n \\\"application\\\": null,\\n \\\"application_fee_amount\\\": null,\\n \\\"automatic_payment_methods\\\": null,\\n \\\"canceled_at\\\": null,\\n \\\"cancellation_reason\\\": null,\\n \\\"capture_method\\\": \\\"automatic\\\",\\n \\\"client_secret\\\": \\\"pi_3OXInzD5R7gDAGff1cGAxxHo_secret_E2nuQt3TQz1PbCGT8B6MiWLGu\\\",\\n \\\"confirmation_method\\\": \\\"automatic\\\",\\n \\\"created\\\": 1704958559,\\n \\\"currency\\\": \\\"usd\\\",\\n \\\"customer\\\": \\\"cus_OuQL3sWtKEn0Cs\\\",\\n \\\"description\\\": \\\"Hello this is description\\\",\\n \\\"invoice\\\": null,\\n \\\"last_payment_error\\\": null,\\n \\\"latest_charge\\\": null,\\n \\\"livemode\\\": false,\\n \\\"metadata\\\": {\\n \\\"order_id\\\": \\\"pay_yfkCogrWxVbB8O0biPkh_1\\\"\\n },\\n \\\"next_action\\\": {\\n \\\"redirect_to_url\\\": {\\n \\\"return_url\\\": \\\"https://sandbox.hyperswitch.io/payments/pay_yfkCogrWxVbB8O0biPkh/Allconnector123/redirect/response/stripe\\\",\\n \\\"url\\\": \\\"https://hooks.stripe.com/redirect/authenticate/src_1OXIo0D5R7gDAGffxkofsikB?client_secret=src_client_secret_1P7sv3nHuAc684vjLZlUhwT1&source_redirect_slug=test_YWNjdF8xTTdmVGFENVI3Z0RBR2ZmLF9QTTBwNkJKN01LOWIzeFA3bkMxNjhCd2tra01oUnZ50100WMdcNcbT\\\"\\n },\\n \\\"type\\\": \\\"redirect_to_url\\\"\\n },\\n \\\"on_behalf_of\\\": null,\\n \\\"payment_method\\\": \\\"pm_1OXInzD5R7gDAGffpXWPgsBW\\\",\\n \\\"payment_method_configuration_details\\\": null,\\n \\\"payment_method_options\\\": {\\n \\\"card\\\": {\\n \\\"installments\\\": null,\\n \\\"mandate_options\\\": null,\\n \\\"network\\\": null,\\n \\\"request_three_d_secure\\\": \\\"any\\\"\\n }\\n },\\n \\\"payment_method_types\\\": [\\n \\\"card\\\"\\n ],\\n \\\"processing\\\": null,\\n \\\"receipt_email\\\": null,\\n \\\"review\\\": null,\\n \\\"setup_future_usage\\\": null,\\n \\\"shipping\\\": {\\n \\\"address\\\": {\\n \\\"city\\\": \\\"Banglore\\\",\\n \\\"country\\\": \\\"US\\\",\\n \\\"line1\\\": \\\"sdsdfsdf\\\",\\n \\\"line2\\\": \\\"hsgdbhd\\\",\\n \\\"postal_code\\\": \\\"571201\\\",\\n \\\"state\\\": \\\"zsaasdas\\\"\\n },\\n \\\"carrier\\\": null,\\n \\\"name\\\": \\\"Bopanna MJ\\\",\\n \\\"phone\\\": \\\"+1123456789\\\",\\n \\\"tracking_number\\\": null\\n },\\n \\\"source\\\": null,\\n \\\"statement_descriptor\\\": null,\\n \\\"statement_descriptor_suffix\\\": null,\\n \\\"status\\\": \\\"requires_action\\\",\\n \\\"transfer_data\\\": null,\\n \\\"transfer_group\\\": null\\n}","error":null,"status_code":0,"latency":891,"created_at":"2024-01-11T07:36:00.507Z","method":"POST"}]` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
398c5ed51e0547504c3dfbd1d7c23568337e7d1c
juspay/hyperswitch
juspay__hyperswitch-3307
Bug: [FEATURE] [BOA/Cybersource] Include merchant metadata in capture and void requests ### Feature Description Include merchant metadata in capture and void requests for connectors BOA and Cybersource. ### Possible Implementation Include merchant metadata in capture and void requests for connectors BOA and Cybersource. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 71a44b5a6e6..e024eb7a501 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -988,6 +988,8 @@ pub struct OrderInformation { pub struct BankOfAmericaCaptureRequest { order_information: OrderInformation, client_reference_information: ClientReferenceInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>> @@ -997,6 +999,10 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>> fn try_from( value: &BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { + let merchant_defined_information = + value.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); Ok(Self { order_information: OrderInformation { amount_details: Amount { @@ -1007,6 +1013,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>> client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), }, + merchant_defined_information, }) } } @@ -1016,6 +1023,9 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>> pub struct BankOfAmericaVoidRequest { client_reference_information: ClientReferenceInformation, reversal_information: ReversalInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, + // The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works! } #[derive(Debug, Serialize)] @@ -1032,6 +1042,10 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCancelRouterData>> fn try_from( value: &BankOfAmericaRouterData<&types::PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { + let merchant_defined_information = + value.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), @@ -1054,6 +1068,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCancelRouterData>> field_name: "Cancellation Reason", })?, }, + merchant_defined_information, }) } } diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index e46833d2ecd..bc69fb78129 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -837,6 +837,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> pub struct CybersourcePaymentsCaptureRequest { processing_information: ProcessingInformation, order_information: OrderInformationWithBill, + client_reference_information: ClientReferenceInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] @@ -853,6 +856,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>> fn try_from( item: &CybersourceRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); Ok(Self { processing_information: ProcessingInformation { capture_options: Some(CaptureOptions { @@ -873,6 +880,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>> }, bill_to: None, }, + client_reference_information: ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }, + merchant_defined_information, }) } } @@ -918,6 +929,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout pub struct CybersourceVoidRequest { client_reference_information: ClientReferenceInformation, reversal_information: ReversalInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, + // The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works! } #[derive(Debug, Serialize)] @@ -932,6 +946,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCancelRouterData>> for Cyber fn try_from( value: &CybersourceRouterData<&types::PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { + let merchant_defined_information = + value.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), @@ -954,6 +972,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCancelRouterData>> for Cyber field_name: "Cancellation Reason", })?, }, + merchant_defined_information, }) } } @@ -1591,6 +1610,7 @@ impl<F> #[serde(rename_all = "camelCase")] pub struct CybersourceRefundRequest { order_information: OrderInformation, + client_reference_information: ClientReferenceInformation, } impl<F> TryFrom<&CybersourceRouterData<&types::RefundsRouterData<F>>> for CybersourceRefundRequest { @@ -1605,6 +1625,9 @@ impl<F> TryFrom<&CybersourceRouterData<&types::RefundsRouterData<F>>> for Cybers currency: item.router_data.request.currency, }, }, + client_reference_information: ClientReferenceInformation { + code: Some(item.router_data.request.refund_id.clone()), + }, }) } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7b7d64a5f81..09bb203d939 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1223,6 +1223,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureD None => None, }, browser_info, + metadata: payment_data.payment_intent.metadata, }) } } @@ -1257,6 +1258,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelDa cancellation_reason: payment_data.payment_attempt.cancellation_reason, connector_meta: payment_data.payment_attempt.connector_metadata, browser_info, + metadata: payment_data.payment_intent.metadata, }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 2225c2965bc..7cd45a0192f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -428,6 +428,8 @@ pub struct PaymentsCaptureData { pub multiple_capture_data: Option<MultipleCaptureRequestData>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, + pub metadata: Option<pii::SecretSerdeValue>, + // This metadata is used to store the metadata shared during the payment intent request. } #[derive(Debug, Clone, Default)] @@ -542,6 +544,8 @@ pub struct PaymentsCancelData { pub cancellation_reason: Option<String>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, + pub metadata: Option<pii::SecretSerdeValue>, + // This metadata is used to store the metadata shared during the payment intent request. } #[derive(Debug, Default, Clone)]
2024-01-10T11:09:41Z
## 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 --> Include merchant metadata in capture and void requests for connectors BOA and Cybersource. ### 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/3307 ## 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 can be done by creating 2 manual authorized payments for each BOA and Cybersource. While creating these payments you should pass metadata in the requests. ``` "metadata": { "count_tickets": 1, "transaction_number": "5590043" }, ``` Then you should void one payment and capture the other. You should then be able to see this metadata in merchantDefinedInformation in BOA/Cybersource Dashboard. ![image](https://github.com/juspay/hyperswitch/assets/41580413/4ce708b8-8714-4dd3-8535-c480fdac3f30) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
612f8d9d5f5bcba78aa64c3128cc72be0f2860ea
juspay/hyperswitch
juspay__hyperswitch-3311
Bug: audit trail - add webhook events ### Webhook Events Audit trail Build a webhook events audit trail endpoint for fetching all events from `webhook_events_audit` table for ops audit trail. ![Image](https://github.com/juspay/hyperswitch/assets/21202349/3ae37c76-117e-46af-8e5c-3c9b74410efa) can refer to the existing API Events audit trail implementation [here](https://github.com/juspay/hyperswitch/blob/main/crates/analytics/src/api_event/events.rs) ``` curl --location 'https://sandbox.hyperswitch.io/analytics/v1/api_event_logs?type=Payment&payment_id=pay_yEsFwSqi6Umv8LVGFFPD' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjBmZDAyNzAtNTE1MS00MWVhLWJiMWItMGY0ZWExZGNmYjQzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjg5OTI0ODQzIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNzA0ODgyODg5LCJvcmdfaWQiOiJvcmdfRk5ZWjhQaE5CQjdtV1hodWxWQW0ifQ.LCgIW8uMGVo2WRFt2irzQ1D8sHuRBSbeRkTGt1qxsXM' ``` The API contract would involve a simple `GET analytics/v1/webhook_event_logs` path. with similar response format as above curl request
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 964486c9364..b8fd5e6a35d 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -21,6 +21,7 @@ use crate::{ filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, + outgoing_webhook_event::events::OutgoingWebhookLogsResult, sdk_events::events::SdkEventsResult, types::TableEngine, }; @@ -120,6 +121,7 @@ impl AnalyticsDataSource for ClickhouseClient { } AnalyticsCollection::SdkEvents => TableEngine::BasicTree, AnalyticsCollection::ApiEvents => TableEngine::BasicTree, + AnalyticsCollection::OutgoingWebhookEvent => TableEngine::BasicTree, } } } @@ -145,6 +147,10 @@ impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} +impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics + for ClickhouseClient +{ +} #[derive(Debug, serde::Serialize)] struct CkhQuery { @@ -302,6 +308,18 @@ impl TryInto<ApiEventFilter> for serde_json::Value { } } +impl TryInto<OutgoingWebhookLogsResult> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<OutgoingWebhookLogsResult, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse OutgoingWebhookLogsResult in clickhouse results", + )) + } +} + impl ToSql<ClickhouseClient> for PrimitiveDateTime { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { let format = @@ -326,6 +344,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::SdkEvents => Ok("sdk_events_dist".to_string()), Self::ApiEvents => Ok("api_audit_log".to_string()), Self::PaymentIntent => Ok("payment_intents_dist".to_string()), + Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), } } } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 24da77f84f2..8529807a1a1 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -7,6 +7,7 @@ mod query; pub mod refunds; pub mod api_event; +pub mod outgoing_webhook_event; pub mod sdk_events; mod sqlx; mod types; diff --git a/crates/analytics/src/outgoing_webhook_event.rs b/crates/analytics/src/outgoing_webhook_event.rs new file mode 100644 index 00000000000..9919d8bbb0f --- /dev/null +++ b/crates/analytics/src/outgoing_webhook_event.rs @@ -0,0 +1,6 @@ +mod core; +pub mod events; + +pub trait OutgoingWebhookEventAnalytics: events::OutgoingWebhookLogsFilterAnalytics {} + +pub use self::core::outgoing_webhook_events_core; diff --git a/crates/analytics/src/outgoing_webhook_event/core.rs b/crates/analytics/src/outgoing_webhook_event/core.rs new file mode 100644 index 00000000000..5024cc70ec1 --- /dev/null +++ b/crates/analytics/src/outgoing_webhook_event/core.rs @@ -0,0 +1,27 @@ +use api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest; +use common_utils::errors::ReportSwitchExt; +use error_stack::{IntoReport, ResultExt}; + +use super::events::{get_outgoing_webhook_event, OutgoingWebhookLogsResult}; +use crate::{errors::AnalyticsResult, types::FiltersError, AnalyticsProvider}; + +pub async fn outgoing_webhook_events_core( + pool: &AnalyticsProvider, + req: OutgoingWebhookLogsRequest, + merchant_id: String, +) -> AnalyticsResult<Vec<OutgoingWebhookLogsResult>> { + let data = match pool { + AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented( + "Outgoing Webhook Events Logs not implemented for SQLX", + )) + .into_report() + .attach_printable("SQL Analytics is not implemented for Outgoing Webhook Events"), + AnalyticsProvider::Clickhouse(ckh_pool) + | AnalyticsProvider::CombinedSqlx(_, ckh_pool) + | AnalyticsProvider::CombinedCkh(_, ckh_pool) => { + get_outgoing_webhook_event(&merchant_id, req, ckh_pool).await + } + } + .switch()?; + Ok(data) +} diff --git a/crates/analytics/src/outgoing_webhook_event/events.rs b/crates/analytics/src/outgoing_webhook_event/events.rs new file mode 100644 index 00000000000..e742387e1eb --- /dev/null +++ b/crates/analytics/src/outgoing_webhook_event/events.rs @@ -0,0 +1,90 @@ +use api_models::analytics::{outgoing_webhook_event::OutgoingWebhookLogsRequest, Granularity}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; +pub trait OutgoingWebhookLogsFilterAnalytics: LoadRow<OutgoingWebhookLogsResult> {} + +pub async fn get_outgoing_webhook_event<T>( + merchant_id: &String, + query_param: OutgoingWebhookLogsRequest, + pool: &T, +) -> FiltersResult<Vec<OutgoingWebhookLogsResult>> +where + T: AnalyticsDataSource + OutgoingWebhookLogsFilterAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::OutgoingWebhookEvent); + query_builder.add_select_column("*").switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + query_builder + .add_filter_clause("payment_id", query_param.payment_id) + .switch()?; + + if let Some(event_id) = query_param.event_id { + query_builder + .add_filter_clause("event_id", &event_id) + .switch()?; + } + if let Some(refund_id) = query_param.refund_id { + query_builder + .add_filter_clause("refund_id", &refund_id) + .switch()?; + } + if let Some(dispute_id) = query_param.dispute_id { + query_builder + .add_filter_clause("dispute_id", &dispute_id) + .switch()?; + } + if let Some(mandate_id) = query_param.mandate_id { + query_builder + .add_filter_clause("mandate_id", &mandate_id) + .switch()?; + } + if let Some(payment_method_id) = query_param.payment_method_id { + query_builder + .add_filter_clause("payment_method_id", &payment_method_id) + .switch()?; + } + if let Some(attempt_id) = query_param.attempt_id { + query_builder + .add_filter_clause("attempt_id", &attempt_id) + .switch()?; + } + //TODO!: update the execute_query function to return reports instead of plain errors... + query_builder + .execute_query::<OutgoingWebhookLogsResult, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct OutgoingWebhookLogsResult { + pub merchant_id: String, + pub event_id: String, + pub event_type: String, + pub outgoing_webhook_event_type: String, + pub payment_id: String, + pub refund_id: Option<String>, + pub attempt_id: Option<String>, + pub dispute_id: Option<String>, + pub payment_method_id: Option<String>, + pub mandate_id: Option<String>, + pub content: Option<String>, + pub is_error: bool, + pub error: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, +} diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index cdd2647e4e7..e32b85a5367 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -429,6 +429,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection { Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::PaymentIntent => Ok("payment_intent".to_string()), + Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?, } } } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 8b1bdbd1ab9..8da4655e255 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -26,6 +26,7 @@ pub enum AnalyticsCollection { SdkEvents, ApiEvents, PaymentIntent, + OutgoingWebhookEvent, } #[allow(dead_code)] diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 0263427b0fd..e0d3fa671b6 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -12,6 +12,7 @@ use self::{ pub use crate::payments::TimeRange; pub mod api_event; +pub mod outgoing_webhook_event; pub mod payments; pub mod refunds; pub mod sdk_events; diff --git a/crates/api_models/src/analytics/outgoing_webhook_event.rs b/crates/api_models/src/analytics/outgoing_webhook_event.rs new file mode 100644 index 00000000000..b6f0aca056f --- /dev/null +++ b/crates/api_models/src/analytics/outgoing_webhook_event.rs @@ -0,0 +1,10 @@ +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct OutgoingWebhookLogsRequest { + pub payment_id: String, + pub event_id: Option<String>, + pub refund_id: Option<String>, + pub dispute_id: Option<String>, + pub mandate_id: Option<String>, + pub payment_method_id: Option<String>, + pub attempt_id: Option<String>, +} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 457d3fde05b..6d9bd5db342 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -17,7 +17,9 @@ use common_utils::{ use crate::{ admin::*, - analytics::{api_event::*, sdk_events::*, *}, + analytics::{ + api_event::*, outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, *, + }, api_keys::*, cards_info::*, disputes::*, @@ -89,7 +91,8 @@ impl_misc_api_event_type!( ApiLogsRequest, GetApiEventMetricRequest, SdkEventsRequest, - ReportRequest + ReportRequest, + OutgoingWebhookLogsRequest ); #[cfg(feature = "stripe")] diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index f31e908e0dc..c62de5bd29a 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -4,7 +4,7 @@ pub mod routes { use actix_web::{web, Responder, Scope}; use analytics::{ api_event::api_events_core, errors::AnalyticsError, lambda_utils::invoke_lambda, - sdk_events::sdk_events_core, + outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core, }; use api_models::analytics::{ GenerateReportRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest, @@ -71,6 +71,10 @@ pub mod routes { ) .service(web::resource("api_event_logs").route(web::get().to(get_api_events))) .service(web::resource("sdk_event_logs").route(web::post().to(get_sdk_events))) + .service( + web::resource("outgoing_webhook_event_logs") + .route(web::get().to(get_outgoing_webhook_events)), + ) .service( web::resource("filters/api_events") .route(web::post().to(get_api_event_filters)), @@ -314,6 +318,30 @@ pub mod routes { .await } + pub async fn get_outgoing_webhook_events( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Query< + api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest, + >, + ) -> impl Responder { + let flow = AnalyticsFlow::GetOutgoingWebhookEvents; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + outgoing_webhook_events_core(&state.pool, req, auth.merchant_account.merchant_id) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + pub async fn get_sdk_events( state: web::Data<AppState>, req: actix_web::HttpRequest, diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 3c7ba8b93df..0127d07170f 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -52,6 +52,7 @@ pub enum AnalyticsFlow { GenerateRefundReport, GetApiEventMetrics, GetApiEventFilters, + GetOutgoingWebhookEvents, } impl FlowMetric for AnalyticsFlow {}
2024-01-10T11:16:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description adding GET api for query to fetch outgoing webhook events log by specified filters **Filter:** ```payment_id: String``` ```event_id: Option<String>``` ```refund_id: Option<String>``` ```dispute_id: Option<String>``` ```mandate_id: Option<String>``` ```payment_method_id: Option<String>``` ```attempt_id: Option<String>``` ### 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)? --> **Api Endpoint:** ```http://localhost:8080/analytics/v1/outgoing_webhook_event_logs``` curl attached below with sample response tested on local machine ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ed07c5ba90868a3132ca90d72219db3ba8978232
juspay/hyperswitch
juspay__hyperswitch-3306
Bug: [BUG] Validation for authtype and metadata in payment connector update ### Bug Description We are validating authtype and metadata while creating payment connector account, But we are not validating in update call. ### Expected Behavior When we try to update payment connector, we should validate authtype and metadata. ### Actual Behavior When we try to update payment connector, we are not validating authtype and metadata. ### Steps To Reproduce Try updating payment connector account with wrong metadata and authtype, It doesn't validate. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index e8593581126..fd4cae3a2b9 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1172,6 +1172,34 @@ pub async fn update_payment_connector( field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; + let connector_name = mca.connector_name.as_ref(); + let connector_enum = api_models::enums::Connector::from_str(connector_name) + .into_report() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?; + validate_auth_and_metadata_type(connector_enum, &auth, &req.metadata).map_err( + |err| match *err.current_context() { + errors::ConnectorError::InvalidConnectorName => { + err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The connector name is invalid".to_string(), + }) + } + errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: format!("The {} is invalid", field_name), + }), + errors::ConnectorError::FailedToObtainAuthType => { + err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The auth type is invalid for the connector".to_string(), + }) + } + _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The request body is invalid".to_string(), + }), + }, + )?; let (connector_status, disabled) = validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?;
2024-01-10T10:25:29Z
## 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 --> Adding validation for authtype and metadata in update payment connector call. ### 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 validation for authtype and metadata in update payment connector call. ## 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)Try passing wrong metadata for any connector in update payment connector call <img width="1160" alt="Screenshot 2024-01-10 at 3 51 20 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/8db585b6-9924-41a0-bf32-c3ee12dc5daa"> 2)Try passing wrong authtype for any connector in update payment connector call <img width="1160" alt="Screenshot 2024-01-10 at 3 51 52 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/04d12c2b-5a39-4721-9e3a-8c521a6f99c6"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
01c2de223f60595d77c06a59a40dfe041e02cfee
juspay/hyperswitch
juspay__hyperswitch-3302
Bug: [REFACTOR] Incorporate `hyperswitch_interface` into router Refactor router to incorporate the newly added crate `hyperswitch_interface` for secrets decryption
diff --git a/config/config.example.toml b/config/config.example.toml index 1a132933433..abe3f6b4e08 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -115,12 +115,9 @@ route_to_trace = ["*/confirm"] # 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. -admin_api_key = "test_admin" # admin API key for admin authentication. Only applicable when KMS is disabled. -kms_encrypted_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the admin_api_key. Only applicable when KMS is enabled. -jwt_secret = "secret" # JWT secret used for user authentication. Only applicable when KMS is disabled. -kms_encrypted_jwt_secret = "" # Base64-encoded (KMS encrypted) ciphertext of the jwt_secret. Only applicable when KMS is enabled. -recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authentication. Only applicable when KMS is disabled. -kms_encrypted_recon_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the recon_admin_api_key. Only applicable when KMS is enabled +admin_api_key = "test_admin" # admin API key for admin authentication. +jwt_secret = "secret" # JWT secret used for user authentication. +recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authentication. # Locker settings contain details for accessing a card locker, a # PCI Compliant storage entity which stores payment method information @@ -156,8 +153,6 @@ outgoing_enabled = true validity = 1 [api_keys] -# Base64-encoded (KMS encrypted) ciphertext of the API key hashing key -kms_encrypted_hash_key = "" # Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating hashes of API keys hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" @@ -322,11 +317,6 @@ paypal = { currency = "USD,INR", country = "US" } # ^------------------------------- any valid payment method type (can be multiple) (for cards this should be card_network) # If either currency or country isn't provided then, all possible values are accepted -# AWS KMS configuration. Only applicable when the `aws_kms` feature flag is enabled. -[kms] -key_id = "" # The AWS key ID used by the KMS SDK for decrypting data. -region = "" # The AWS region used by the KMS SDK for decrypting data. - [cors] max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached. origins = "http://localhost:8080" # List of origins that are allowed to make requests. @@ -568,3 +558,17 @@ file_storage_backend = "aws_s3" # File storage backend to be used [file_storage.aws_s3] region = "us-east-1" # The AWS region used by the AWS S3 for file storage bucket_name = "bucket1" # The AWS S3 bucket name for file storage + +[secrets_management] +secrets_manager = "aws_kms" # Secrets manager client to be used + +[secrets_management.aws_kms] +key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. +region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. + +[encryption_management] +encryption_manager = "aws_kms" # Encryption manager client to be used + +[encryption_management.aws_kms] +key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. +region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 39bf7060b66..c8c118d9827 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -21,8 +21,7 @@ connection_timeout = 10 # Timeout for database connection in seconds queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 client [api_keys] -kms_encrypted_hash_key = "base64_encoded_ciphertext" # Base64-encoded (KMS encrypted) ciphertext of the API key hashing key -hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # API key hashing key. Only applicable when KMS is disabled. +hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # API key hashing key. [applepay_decrypt_keys] apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" # Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate @@ -99,11 +98,6 @@ vault_encryption_key = "" # public key in pem format, corresponding privat rust_locker_encryption_key = "" # public key in pem format, corresponding private key in rust locker vault_private_key = "" # private key in pem format, corresponding public key in rust locker -# KMS configuration. Only applicable when the `kms` feature flag is enabled. -[kms] -key_id = "" # The AWS key ID used by the KMS SDK for decrypting data. -region = "" # The AWS region used by the KMS SDK for decrypting data. - # Locker settings contain details for accessing a card locker, a # PCI Compliant storage entity which stores payment method information # like card details @@ -201,12 +195,9 @@ region = "report_download_config_region" # Region of the buc # 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. -admin_api_key = "test_admin" # admin API key for admin authentication. Only applicable when KMS is disabled. -kms_encrypted_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the admin_api_key. Only applicable when KMS is enabled. -jwt_secret = "secret" # JWT secret used for user authentication. Only applicable when KMS is disabled. -kms_encrypted_jwt_secret = "" # Base64-encoded (KMS encrypted) ciphertext of the jwt_secret. Only applicable when KMS is enabled. -recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authentication. Only applicable when KMS is disabled. -kms_encrypted_recon_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the recon_admin_api_key. Only applicable when KMS is enabled +admin_api_key = "test_admin" # admin API key for admin authentication. +jwt_secret = "secret" # JWT secret used for user authentication. +recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authentication. # Server configuration [server] @@ -219,3 +210,17 @@ host = "127.0.0.1" shutdown_timeout = 30 # HTTP Request body limit. Defaults to 32kB request_body_limit = 32_768 + +[secrets_management] +secrets_manager = "aws_kms" # Secrets manager client to be used + +[secrets_management.aws_kms] +key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. +region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. + +[encryption_management] +encryption_manager = "aws_kms" # Encryption manager client to be used + +[encryption_management.aws_kms] +key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. +region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 725c6a123f1..2eea5b513cc 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -8,9 +8,7 @@ readme = "README.md" license.workspace = true [features] -release = ["aws_kms", "vergen"] -aws_kms = ["external_services/aws_kms"] -hashicorp-vault = ["external_services/hashicorp-vault"] +release = ["vergen", "external_services/aws_kms"] vergen = ["router_env/vergen"] [dependencies] diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs index 377fdcd1569..64e66619d74 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -17,8 +17,7 @@ async fn main() -> DrainerResult<()> { let state = settings::AppState::new(conf.clone()).await; - let store = services::Store::new(&state.conf, false).await; - let store = std::sync::Arc::new(store); + let store = std::sync::Arc::new(services::Store::new(&state.conf, false).await); #[cfg(feature = "vergen")] println!("Starting drainer (Version: {})", router_env::git_tag!()); diff --git a/crates/drainer/src/secrets_transformers.rs b/crates/drainer/src/secrets_transformers.rs index c0447725a79..4ffb584a152 100644 --- a/crates/drainer/src/secrets_transformers.rs +++ b/crates/drainer/src/secrets_transformers.rs @@ -11,7 +11,7 @@ use crate::settings::{Database, Settings}; impl SecretsHandler for Database { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, - secret_management_client: Box<dyn SecretManagementInterface>, + secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let secured_db_config = value.get_inner(); let raw_db_password = secret_management_client @@ -28,10 +28,9 @@ impl SecretsHandler for Database { /// # Panics /// /// Will panic even if fetching raw secret fails for at least one config value -#[allow(clippy::unwrap_used)] pub async fn fetch_raw_secrets( conf: Settings<SecuredSecret>, - secret_management_client: Box<dyn SecretManagementInterface>, + secret_management_client: &dyn SecretManagementInterface, ) -> Settings<RawSecret> { #[allow(clippy::expect_used)] let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client) diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index ec24c472af2..e68ede9e8b2 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -47,7 +47,7 @@ impl AppState { .expect("Failed to create secret management client"); let raw_conf = - secrets_transformers::fetch_raw_secrets(conf, secret_management_client).await; + secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await; #[allow(clippy::expect_used)] let encryption_client = raw_conf diff --git a/crates/external_services/src/aws_kms.rs b/crates/external_services/src/aws_kms.rs index 3e5353fd9e3..a01062f26e8 100644 --- a/crates/external_services/src/aws_kms.rs +++ b/crates/external_services/src/aws_kms.rs @@ -2,6 +2,4 @@ pub mod core; -pub mod decrypt; - pub mod implementers; diff --git a/crates/external_services/src/aws_kms/core.rs b/crates/external_services/src/aws_kms/core.rs index c01bcbfb094..d211f1def9b 100644 --- a/crates/external_services/src/aws_kms/core.rs +++ b/crates/external_services/src/aws_kms/core.rs @@ -7,23 +7,9 @@ use aws_sdk_kms::{config::Region, primitives::Blob, Client}; use base64::Engine; use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; use router_env::logger; -#[cfg(feature = "hashicorp-vault")] -use crate::hashicorp_vault; -use crate::{aws_kms::decrypt::AwsKmsDecrypt, consts, metrics}; - -pub(crate) static AWS_KMS_CLIENT: tokio::sync::OnceCell<AwsKmsClient> = - tokio::sync::OnceCell::const_new(); - -/// Returns a shared AWS KMS client, or initializes a new one if not previously initialized. -#[inline] -pub async fn get_aws_kms_client(config: &AwsKmsConfig) -> &'static AwsKmsClient { - AWS_KMS_CLIENT - .get_or_init(|| AwsKmsClient::new(config)) - .await -} +use crate::{consts, metrics}; /// Configuration parameters required for constructing a [`AwsKmsClient`]. #[derive(Clone, Debug, Default, serde::Deserialize)] @@ -188,69 +174,6 @@ impl AwsKmsConfig { } } -/// A wrapper around a AWS KMS value that can be decrypted. -#[derive(Clone, Debug, Default, serde::Deserialize, Eq, PartialEq)] -#[serde(transparent)] -pub struct AwsKmsValue(Secret<String>); - -impl common_utils::ext_traits::ConfigExt for AwsKmsValue { - fn is_empty_after_trim(&self) -> bool { - self.0.peek().is_empty_after_trim() - } -} - -impl From<String> for AwsKmsValue { - fn from(value: String) -> Self { - Self(Secret::new(value)) - } -} - -impl From<Secret<String>> for AwsKmsValue { - fn from(value: Secret<String>) -> Self { - Self(value) - } -} - -#[cfg(feature = "hashicorp-vault")] -#[async_trait::async_trait] -impl hashicorp_vault::decrypt::VaultFetch for AwsKmsValue { - async fn fetch_inner<En>( - self, - client: &hashicorp_vault::core::HashiCorpVault, - ) -> error_stack::Result<Self, hashicorp_vault::core::HashiCorpError> - where - for<'a> En: hashicorp_vault::core::Engine< - ReturnType<'a, String> = std::pin::Pin< - Box< - dyn std::future::Future< - Output = error_stack::Result< - String, - hashicorp_vault::core::HashiCorpError, - >, - > + Send - + 'a, - >, - >, - > + 'a, - { - self.0.fetch_inner::<En>(client).await.map(AwsKmsValue) - } -} - -#[async_trait::async_trait] -impl AwsKmsDecrypt for &AwsKmsValue { - type Output = String; - async fn decrypt_inner( - self, - aws_kms_client: &AwsKmsClient, - ) -> CustomResult<Self::Output, AwsKmsError> { - aws_kms_client - .decrypt(self.0.peek()) - .await - .attach_printable("Failed to decrypt AWS KMS value") - } -} - #[cfg(test)] mod tests { #![allow(clippy::expect_used)] diff --git a/crates/external_services/src/aws_kms/decrypt.rs b/crates/external_services/src/aws_kms/decrypt.rs deleted file mode 100644 index 47edb8f958f..00000000000 --- a/crates/external_services/src/aws_kms/decrypt.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! Decrypting data using the AWS KMS SDK. -use common_utils::errors::CustomResult; - -use crate::aws_kms::core::{AwsKmsClient, AwsKmsError, AWS_KMS_CLIENT}; - -#[async_trait::async_trait] -/// This trait performs in place decryption of the structure on which this is implemented -pub trait AwsKmsDecrypt { - /// The output type of the decryption - type Output; - /// Decrypts the structure given a AWS KMS client - async fn decrypt_inner( - self, - aws_kms_client: &AwsKmsClient, - ) -> CustomResult<Self::Output, AwsKmsError> - where - Self: Sized; - - /// Tries to use the Singleton client to decrypt the structure - async fn try_decrypt_inner(self) -> CustomResult<Self::Output, AwsKmsError> - where - Self: Sized, - { - let client = AWS_KMS_CLIENT - .get() - .ok_or(AwsKmsError::AwsKmsClientNotInitialized)?; - self.decrypt_inner(client).await - } -} diff --git a/crates/external_services/src/hashicorp_vault.rs b/crates/external_services/src/hashicorp_vault.rs index 5a3ba539689..6bf234ff420 100644 --- a/crates/external_services/src/hashicorp_vault.rs +++ b/crates/external_services/src/hashicorp_vault.rs @@ -2,6 +2,4 @@ pub mod core; -pub mod decrypt; - pub mod implementers; diff --git a/crates/external_services/src/hashicorp_vault/decrypt.rs b/crates/external_services/src/hashicorp_vault/decrypt.rs deleted file mode 100644 index 650b219841f..00000000000 --- a/crates/external_services/src/hashicorp_vault/decrypt.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! Utilities for supporting decryption of data - -use std::{future::Future, pin::Pin}; - -use masking::ExposeInterface; - -use crate::hashicorp_vault::core::{Engine, HashiCorpError, HashiCorpVault}; - -/// A trait for types that can be asynchronously fetched and decrypted from HashiCorp Vault. -#[async_trait::async_trait] -pub trait VaultFetch: Sized { - /// Asynchronously decrypts the inner content of the type. - /// - /// # Returns - /// - /// An `Result<Self, super::HashiCorpError>` representing the decrypted instance if successful, - /// or an `super::HashiCorpError` with details about the encountered error. - /// - async fn fetch_inner<En>( - self, - client: &HashiCorpVault, - ) -> error_stack::Result<Self, HashiCorpError> - where - for<'a> En: Engine< - ReturnType<'a, String> = Pin< - Box< - dyn Future<Output = error_stack::Result<String, HashiCorpError>> - + Send - + 'a, - >, - >, - > + 'a; -} - -#[async_trait::async_trait] -impl VaultFetch for masking::Secret<String> { - async fn fetch_inner<En>( - self, - client: &HashiCorpVault, - ) -> error_stack::Result<Self, HashiCorpError> - where - for<'a> En: Engine< - ReturnType<'a, String> = Pin< - Box< - dyn Future<Output = error_stack::Result<String, HashiCorpError>> - + Send - + 'a, - >, - >, - > + 'a, - { - client.fetch::<En, Self>(self.expose()).await - } -} diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs index a0915b8de69..d823eba8700 100644 --- a/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs +++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs @@ -16,6 +16,6 @@ where /// Construct `Self` with raw secret value and transitions its type from `SecuredSecret` to `RawSecret` async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, - kms_client: Box<dyn SecretManagementInterface>, + kms_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError>; } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index c511947cd1e..5dbeb1bb199 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,13 +10,10 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] -aws_s3 = ["external_services/aws_s3"] -aws_kms = ["external_services/aws_kms"] -hashicorp-vault = ["external_services/hashicorp-vault"] email = ["external_services/email", "scheduler/email", "olap"] frm = [] stripe = ["dep:serde_qs"] -release = ["aws_kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] +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"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] diff --git a/crates/router/src/configs.rs b/crates/router/src/configs.rs index d069c89b82e..f7514a312a4 100644 --- a/crates/router/src/configs.rs +++ b/crates/router/src/configs.rs @@ -1,7 +1,8 @@ -#[cfg(feature = "aws_kms")] -pub mod aws_kms; +use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret; + mod defaults; -#[cfg(feature = "hashicorp-vault")] -pub mod hc_vault; +pub mod secrets_transformers; pub mod settings; mod validations; + +pub type Settings = settings::Settings<RawSecret>; diff --git a/crates/router/src/configs/aws_kms.rs b/crates/router/src/configs/aws_kms.rs deleted file mode 100644 index 9bb5fcc6f20..00000000000 --- a/crates/router/src/configs/aws_kms.rs +++ /dev/null @@ -1,110 +0,0 @@ -use common_utils::errors::CustomResult; -use external_services::aws_kms::{ - core::{AwsKmsClient, AwsKmsError}, - decrypt::AwsKmsDecrypt, -}; -use masking::ExposeInterface; - -use crate::configs::settings; - -#[async_trait::async_trait] -impl AwsKmsDecrypt for settings::Jwekey { - type Output = Self; - - async fn decrypt_inner( - mut self, - aws_kms_client: &AwsKmsClient, - ) -> CustomResult<Self::Output, AwsKmsError> { - ( - self.vault_encryption_key, - self.rust_locker_encryption_key, - self.vault_private_key, - self.tunnel_private_key, - ) = tokio::try_join!( - aws_kms_client.decrypt(self.vault_encryption_key), - aws_kms_client.decrypt(self.rust_locker_encryption_key), - aws_kms_client.decrypt(self.vault_private_key), - aws_kms_client.decrypt(self.tunnel_private_key), - )?; - Ok(self) - } -} - -#[async_trait::async_trait] -impl AwsKmsDecrypt for settings::ActiveKmsSecrets { - type Output = Self; - async fn decrypt_inner( - mut self, - aws_kms_client: &AwsKmsClient, - ) -> CustomResult<Self::Output, AwsKmsError> { - self.jwekey = self - .jwekey - .expose() - .decrypt_inner(aws_kms_client) - .await? - .into(); - Ok(self) - } -} - -#[async_trait::async_trait] -impl AwsKmsDecrypt for settings::Database { - type Output = storage_impl::config::Database; - - async fn decrypt_inner( - mut self, - aws_kms_client: &AwsKmsClient, - ) -> CustomResult<Self::Output, AwsKmsError> { - Ok(storage_impl::config::Database { - host: self.host, - port: self.port, - dbname: self.dbname, - username: self.username, - password: self.password.decrypt_inner(aws_kms_client).await?.into(), - pool_size: self.pool_size, - connection_timeout: self.connection_timeout, - queue_strategy: self.queue_strategy, - min_idle: self.min_idle, - max_lifetime: self.max_lifetime, - }) - } -} - -#[cfg(feature = "olap")] -#[async_trait::async_trait] -impl AwsKmsDecrypt for settings::PayPalOnboarding { - type Output = Self; - - async fn decrypt_inner( - mut self, - aws_kms_client: &AwsKmsClient, - ) -> CustomResult<Self::Output, AwsKmsError> { - self.client_id = aws_kms_client - .decrypt(self.client_id.expose()) - .await? - .into(); - self.client_secret = aws_kms_client - .decrypt(self.client_secret.expose()) - .await? - .into(); - self.partner_id = aws_kms_client - .decrypt(self.partner_id.expose()) - .await? - .into(); - Ok(self) - } -} - -#[cfg(feature = "olap")] -#[async_trait::async_trait] -impl AwsKmsDecrypt for settings::ConnectorOnboarding { - type Output = Self; - - async fn decrypt_inner( - mut self, - aws_kms_client: &AwsKmsClient, - ) -> CustomResult<Self::Output, AwsKmsError> { - self.paypal = self.paypal.decrypt_inner(aws_kms_client).await?; - Ok(self) - } -} diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index e56acde78c2..5c2d62b40b8 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -1,10 +1,8 @@ use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms::core::AwsKmsValue; -use super::settings::{ConnectorFields, Password, PaymentMethodType, RequiredFieldFinal}; +use super::settings::{ConnectorFields, PaymentMethodType, RequiredFieldFinal}; impl Default for super::settings::Server { fn default() -> Self { @@ -37,7 +35,7 @@ impl Default for super::settings::Database { fn default() -> Self { Self { username: String::new(), - password: Password::default(), + password: String::new().into(), host: "localhost".into(), port: 5432, dbname: String::new(), @@ -6518,13 +6516,9 @@ impl Default for super::settings::RequiredFields { impl Default for super::settings::ApiKeys { fn default() -> Self { Self { - #[cfg(feature = "aws_kms")] - kms_encrypted_hash_key: AwsKmsValue::default(), - // Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating // hashes of API keys - #[cfg(not(feature = "aws_kms"))] - hash_key: String::new(), + hash_key: String::new().into(), // Specifies the number of days before API key expiry when email reminders should be sent #[cfg(feature = "email")] diff --git a/crates/router/src/configs/hc_vault.rs b/crates/router/src/configs/hc_vault.rs deleted file mode 100644 index fa6596f7494..00000000000 --- a/crates/router/src/configs/hc_vault.rs +++ /dev/null @@ -1,135 +0,0 @@ -use external_services::hashicorp_vault::{ - core::{Engine, HashiCorpError, HashiCorpVault}, - decrypt::VaultFetch, -}; -use masking::ExposeInterface; - -use crate::configs::settings; - -#[async_trait::async_trait] -impl VaultFetch for settings::Jwekey { - async fn fetch_inner<En>( - mut self, - client: &HashiCorpVault, - ) -> error_stack::Result<Self, HashiCorpError> - where - for<'a> En: Engine< - ReturnType<'a, String> = std::pin::Pin< - Box< - dyn std::future::Future< - Output = error_stack::Result<String, HashiCorpError>, - > + Send - + 'a, - >, - >, - > + 'a, - { - ( - self.vault_encryption_key, - self.rust_locker_encryption_key, - self.vault_private_key, - self.tunnel_private_key, - ) = ( - masking::Secret::new(self.vault_encryption_key) - .fetch_inner::<En>(client) - .await? - .expose(), - masking::Secret::new(self.rust_locker_encryption_key) - .fetch_inner::<En>(client) - .await? - .expose(), - masking::Secret::new(self.vault_private_key) - .fetch_inner::<En>(client) - .await? - .expose(), - masking::Secret::new(self.tunnel_private_key) - .fetch_inner::<En>(client) - .await? - .expose(), - ); - Ok(self) - } -} - -#[async_trait::async_trait] -impl VaultFetch for settings::Database { - async fn fetch_inner<En>( - mut self, - client: &HashiCorpVault, - ) -> error_stack::Result<Self, HashiCorpError> - where - for<'a> En: Engine< - ReturnType<'a, String> = std::pin::Pin< - Box< - dyn std::future::Future< - Output = error_stack::Result<String, HashiCorpError>, - > + Send - + 'a, - >, - >, - > + 'a, - { - Ok(Self { - host: self.host, - port: self.port, - dbname: self.dbname, - username: self.username, - password: self.password.fetch_inner::<En>(client).await?, - pool_size: self.pool_size, - connection_timeout: self.connection_timeout, - queue_strategy: self.queue_strategy, - min_idle: self.min_idle, - max_lifetime: self.max_lifetime, - }) - } -} - -#[cfg(feature = "olap")] -#[async_trait::async_trait] -impl VaultFetch for settings::PayPalOnboarding { - async fn fetch_inner<En>( - mut self, - client: &HashiCorpVault, - ) -> error_stack::Result<Self, HashiCorpError> - where - for<'a> En: Engine< - ReturnType<'a, String> = std::pin::Pin< - Box< - dyn std::future::Future< - Output = error_stack::Result<String, HashiCorpError>, - > + Send - + 'a, - >, - >, - > + 'a, - { - self.client_id = self.client_id.fetch_inner::<En>(client).await?; - self.client_secret = self.client_secret.fetch_inner::<En>(client).await?; - self.partner_id = self.partner_id.fetch_inner::<En>(client).await?; - Ok(self) - } -} - -#[cfg(feature = "olap")] -#[async_trait::async_trait] -impl VaultFetch for settings::ConnectorOnboarding { - async fn fetch_inner<En>( - mut self, - client: &HashiCorpVault, - ) -> error_stack::Result<Self, HashiCorpError> - where - for<'a> En: Engine< - ReturnType<'a, String> = std::pin::Pin< - Box< - dyn std::future::Future< - Output = error_stack::Result<String, HashiCorpError>, - > + Send - + 'a, - >, - >, - > + 'a, - { - self.paypal = self.paypal.fetch_inner::<En>(client).await?; - Ok(self) - } -} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs new file mode 100644 index 00000000000..1306cdd80bb --- /dev/null +++ b/crates/router/src/configs/secrets_transformers.rs @@ -0,0 +1,357 @@ +use common_utils::errors::CustomResult; +use hyperswitch_interfaces::secrets_interface::{ + secret_handler::SecretsHandler, + secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, + SecretManagementInterface, SecretsManagementError, +}; + +use crate::settings::{self, Settings}; + +#[async_trait::async_trait] +impl SecretsHandler for settings::Database { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let db = value.get_inner(); + let db_password = secret_management_client + .get_secret(db.password.clone()) + .await?; + + Ok(value.transition_state(|db| Self { + password: db_password, + ..db + })) + } +} + +#[async_trait::async_trait] +impl SecretsHandler for settings::Jwekey { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let jwekey = value.get_inner(); + let ( + vault_encryption_key, + rust_locker_encryption_key, + vault_private_key, + tunnel_private_key, + ) = tokio::try_join!( + secret_management_client.get_secret(jwekey.vault_encryption_key.clone()), + secret_management_client.get_secret(jwekey.rust_locker_encryption_key.clone()), + secret_management_client.get_secret(jwekey.vault_private_key.clone()), + secret_management_client.get_secret(jwekey.tunnel_private_key.clone()) + )?; + Ok(value.transition_state(|_| Self { + vault_encryption_key, + rust_locker_encryption_key, + vault_private_key, + tunnel_private_key, + })) + } +} + +#[cfg(feature = "olap")] +#[async_trait::async_trait] +impl SecretsHandler for settings::ConnectorOnboarding { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let onboarding_config = &value.get_inner().paypal; + + let (client_id, client_secret, partner_id) = tokio::try_join!( + secret_management_client.get_secret(onboarding_config.client_id.clone()), + secret_management_client.get_secret(onboarding_config.client_secret.clone()), + secret_management_client.get_secret(onboarding_config.partner_id.clone()) + )?; + + Ok(value.transition_state(|onboarding_config| Self { + paypal: settings::PayPalOnboarding { + client_id, + client_secret, + partner_id, + ..onboarding_config.paypal + }, + })) + } +} + +#[async_trait::async_trait] +impl SecretsHandler for settings::ForexApi { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let forex_api = value.get_inner(); + + let (api_key, fallback_api_key) = tokio::try_join!( + secret_management_client.get_secret(forex_api.api_key.clone()), + secret_management_client.get_secret(forex_api.fallback_api_key.clone()), + )?; + + Ok(value.transition_state(|forex_api| Self { + api_key, + fallback_api_key, + ..forex_api + })) + } +} + +#[async_trait::async_trait] +impl SecretsHandler for settings::ApiKeys { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let api_keys = value.get_inner(); + + let hash_key = secret_management_client + .get_secret(api_keys.hash_key.clone()) + .await?; + + #[cfg(feature = "email")] + let expiry_reminder_days = api_keys.expiry_reminder_days.clone(); + + Ok(value.transition_state(|_| Self { + hash_key, + #[cfg(feature = "email")] + expiry_reminder_days, + })) + } +} + +#[async_trait::async_trait] +impl SecretsHandler for settings::ApplePayDecryptConifg { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let applepay_decrypt_keys = value.get_inner(); + + let ( + apple_pay_ppc, + apple_pay_ppc_key, + apple_pay_merchant_cert, + apple_pay_merchant_cert_key, + ) = tokio::try_join!( + secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc.clone()), + secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc_key.clone()), + secret_management_client + .get_secret(applepay_decrypt_keys.apple_pay_merchant_cert.clone()), + secret_management_client + .get_secret(applepay_decrypt_keys.apple_pay_merchant_cert_key.clone()), + )?; + + Ok(value.transition_state(|_| Self { + apple_pay_ppc, + apple_pay_ppc_key, + apple_pay_merchant_cert, + apple_pay_merchant_cert_key, + })) + } +} + +#[async_trait::async_trait] +impl SecretsHandler for settings::ApplepayMerchantConfigs { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let applepay_merchant_configs = value.get_inner(); + + let (merchant_cert, merchant_cert_key, common_merchant_identifier) = tokio::try_join!( + secret_management_client.get_secret(applepay_merchant_configs.merchant_cert.clone()), + secret_management_client + .get_secret(applepay_merchant_configs.merchant_cert_key.clone()), + secret_management_client + .get_secret(applepay_merchant_configs.common_merchant_identifier.clone()), + )?; + + Ok(value.transition_state(|applepay_merchant_configs| Self { + merchant_cert, + merchant_cert_key, + common_merchant_identifier, + ..applepay_merchant_configs + })) + } +} + +#[async_trait::async_trait] +impl SecretsHandler for settings::PaymentMethodAuth { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let payment_method_auth = value.get_inner(); + + let pm_auth_key = secret_management_client + .get_secret(payment_method_auth.pm_auth_key.clone()) + .await?; + + Ok(value.transition_state(|payment_method_auth| Self { + pm_auth_key, + ..payment_method_auth + })) + } +} + +#[async_trait::async_trait] +impl SecretsHandler for settings::Secrets { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let secrets = value.get_inner(); + let (jwt_secret, admin_api_key, recon_admin_api_key, master_enc_key) = tokio::try_join!( + secret_management_client.get_secret(secrets.jwt_secret.clone()), + secret_management_client.get_secret(secrets.admin_api_key.clone()), + secret_management_client.get_secret(secrets.recon_admin_api_key.clone()), + secret_management_client.get_secret(secrets.master_enc_key.clone()) + )?; + + Ok(value.transition_state(|_| Self { + jwt_secret, + admin_api_key, + recon_admin_api_key, + master_enc_key, + })) + } +} + +/// # Panics +/// +/// Will panic even if kms decryption fails for at least one field +pub(crate) async fn fetch_raw_secrets( + conf: Settings<SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, +) -> Settings<RawSecret> { + #[allow(clippy::expect_used)] + let master_database = + settings::Database::convert_to_raw_secret(conf.master_database, secret_management_client) + .await + .expect("Failed to decrypt master database configuration"); + + #[cfg(feature = "olap")] + #[allow(clippy::expect_used)] + let replica_database = + settings::Database::convert_to_raw_secret(conf.replica_database, secret_management_client) + .await + .expect("Failed to decrypt replica database configuration"); + + #[allow(clippy::expect_used)] + let secrets = settings::Secrets::convert_to_raw_secret(conf.secrets, secret_management_client) + .await + .expect("Failed to decrypt secrets"); + + #[allow(clippy::expect_used)] + let forex_api = + settings::ForexApi::convert_to_raw_secret(conf.forex_api, secret_management_client) + .await + .expect("Failed to decrypt forex api configs"); + + #[allow(clippy::expect_used)] + let jwekey = settings::Jwekey::convert_to_raw_secret(conf.jwekey, secret_management_client) + .await + .expect("Failed to decrypt jwekey configs"); + + #[allow(clippy::expect_used)] + let api_keys = + settings::ApiKeys::convert_to_raw_secret(conf.api_keys, secret_management_client) + .await + .expect("Failed to decrypt api_keys configs"); + + #[cfg(feature = "olap")] + #[allow(clippy::expect_used)] + let connector_onboarding = settings::ConnectorOnboarding::convert_to_raw_secret( + conf.connector_onboarding, + secret_management_client, + ) + .await + .expect("Failed to decrypt connector_onboarding configs"); + + #[allow(clippy::expect_used)] + let applepay_decrypt_keys = settings::ApplePayDecryptConifg::convert_to_raw_secret( + conf.applepay_decrypt_keys, + secret_management_client, + ) + .await + .expect("Failed to decrypt applepay decrypt configs"); + + #[allow(clippy::expect_used)] + let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret( + conf.applepay_merchant_configs, + secret_management_client, + ) + .await + .expect("Failed to decrypt applepay merchant configs"); + + #[allow(clippy::expect_used)] + let payment_method_auth = settings::PaymentMethodAuth::convert_to_raw_secret( + conf.payment_method_auth, + secret_management_client, + ) + .await + .expect("Failed to decrypt payment method auth configs"); + + Settings { + server: conf.server, + master_database, + redis: conf.redis, + log: conf.log, + #[cfg(feature = "kv_store")] + drainer: conf.drainer, + encryption_management: conf.encryption_management, + secrets_management: conf.secrets_management, + proxy: conf.proxy, + env: conf.env, + #[cfg(feature = "olap")] + replica_database, + secrets, + locker: conf.locker, + connectors: conf.connectors, + forex_api, + refund: conf.refund, + eph_key: conf.eph_key, + scheduler: conf.scheduler, + jwekey, + webhooks: conf.webhooks, + pm_filters: conf.pm_filters, + bank_config: conf.bank_config, + api_keys, + file_storage: conf.file_storage, + tokenization: conf.tokenization, + connector_customer: conf.connector_customer, + #[cfg(feature = "dummy_connector")] + dummy_connector: conf.dummy_connector, + #[cfg(feature = "email")] + email: conf.email, + mandates: conf.mandates, + required_fields: conf.required_fields, + delayed_session_response: conf.delayed_session_response, + webhook_source_verification_call: conf.webhook_source_verification_call, + payment_method_auth, + connector_request_reference_id_config: conf.connector_request_reference_id_config, + #[cfg(feature = "payouts")] + payouts: conf.payouts, + applepay_decrypt_keys, + multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors, + applepay_merchant_configs, + lock_settings: conf.lock_settings, + temp_locker_enable_config: conf.temp_locker_enable_config, + payment_link: conf.payment_link, + #[cfg(feature = "olap")] + analytics: conf.analytics, + #[cfg(feature = "kv_store")] + kv_config: conf.kv_config, + #[cfg(feature = "frm")] + frm: conf.frm, + #[cfg(feature = "olap")] + report_download_config: conf.report_download_config, + events: conf.events, + #[cfg(feature = "olap")] + connector_onboarding, + cors: conf.cors, + } +} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 8ed2daef5f3..8fb55491fe4 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -8,12 +8,8 @@ use analytics::ReportConfig; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; #[cfg(feature = "email")] use external_services::email::EmailSettings; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault; use external_services::{ file_storage::FileStorageConfig, managers::{ @@ -21,6 +17,10 @@ use external_services::{ secrets_management::SecretsManagementConfig, }, }; +use hyperswitch_interfaces::secrets_interface::secret_state::{ + SecretState, SecretStateContainer, SecuredSecret, +}; +use masking::Secret; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; @@ -35,10 +35,6 @@ use crate::{ env::{self, logger, Env}, events::EventsConfig, }; -#[cfg(feature = "aws_kms")] -pub type Password = aws_kms::core::AwsKmsValue; -#[cfg(not(feature = "aws_kms"))] -pub type Password = masking::Secret<String>; #[derive(clap::Parser, Default)] #[cfg_attr(feature = "vergen", command(version = router_env::version!()))] @@ -59,48 +55,34 @@ pub enum Subcommand { GenerateOpenapiSpec, } -#[cfg(feature = "aws_kms")] -/// Store the decrypted aws kms secret values for active use in the application -/// Currently using `StrongSecret` won't have any effect as this struct have smart pointers to heap -/// allocations. -/// note: we can consider adding such behaviour in the future with custom implementation -#[derive(Clone)] -pub struct ActiveKmsSecrets { - pub jwekey: masking::Secret<Jwekey>, -} - #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] -pub struct Settings { +pub struct Settings<S: SecretState> { pub server: Server, pub proxy: Proxy, pub env: Env, - pub master_database: Database, + pub master_database: SecretStateContainer<Database, S>, #[cfg(feature = "olap")] - pub replica_database: Database, + pub replica_database: SecretStateContainer<Database, S>, pub redis: RedisSettings, pub log: Log, - pub secrets: Secrets, + pub secrets: SecretStateContainer<Secrets, S>, pub locker: Locker, pub connectors: Connectors, - pub forex_api: ForexApi, + pub forex_api: SecretStateContainer<ForexApi, S>, pub refund: Refund, pub eph_key: EphemeralConfig, pub scheduler: Option<SchedulerSettings>, #[cfg(feature = "kv_store")] pub drainer: DrainerSettings, - pub jwekey: Jwekey, + pub jwekey: SecretStateContainer<Jwekey, S>, pub webhooks: WebhooksSettings, pub pm_filters: ConnectorFilters, pub bank_config: BankRedirectConfig, - pub api_keys: ApiKeys, - #[cfg(feature = "aws_kms")] - pub kms: aws_kms::core::AwsKmsConfig, + pub api_keys: SecretStateContainer<ApiKeys, S>, pub file_storage: FileStorageConfig, pub encryption_management: EncryptionManagementConfig, pub secrets_management: SecretsManagementConfig, - #[cfg(feature = "hashicorp-vault")] - pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] @@ -112,13 +94,13 @@ pub struct Settings { pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub webhook_source_verification_call: WebhookSourceVerificationCall, - pub payment_method_auth: PaymentMethodAuth, + pub payment_method_auth: SecretStateContainer<PaymentMethodAuth, S>, pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig, #[cfg(feature = "payouts")] pub payouts: Payouts, - pub applepay_decrypt_keys: ApplePayDecryptConifg, + pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConifg, S>, pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors, - pub applepay_merchant_configs: ApplepayMerchantConfigs, + pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>, pub lock_settings: LockSettings, pub temp_locker_enable_config: TempLockerEnableConfig, pub payment_link: PaymentLink, @@ -132,7 +114,7 @@ pub struct Settings { pub report_download_config: ReportConfig, pub events: EventsConfig, #[cfg(feature = "olap")] - pub connector_onboarding: ConnectorOnboarding, + pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>, } #[cfg(feature = "frm")] @@ -155,8 +137,8 @@ pub struct PaymentLink { #[serde(default)] pub struct ForexApi { pub local_fetch_retry_count: u64, - pub api_key: masking::Secret<String>, - pub fallback_api_key: masking::Secret<String>, + pub api_key: Secret<String>, + pub fallback_api_key: Secret<String>, /// in ms pub call_delay: i64, /// in ms @@ -170,7 +152,7 @@ pub struct ForexApi { #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodAuth { pub redis_expiry: i64, - pub pm_auth_key: String, + pub pm_auth_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] @@ -191,9 +173,9 @@ pub struct Conversion { #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ApplepayMerchantConfigs { - pub merchant_cert: String, - pub merchant_cert_key: String, - pub common_merchant_identifier: String, + pub merchant_cert: Secret<String>, + pub merchant_cert_key: Secret<String>, + pub common_merchant_identifier: Secret<String>, pub applepay_endpoint: String, } @@ -380,19 +362,10 @@ pub struct RequiredFieldFinal { #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct Secrets { - #[cfg(not(feature = "aws_kms"))] - pub jwt_secret: String, - #[cfg(not(feature = "aws_kms"))] - pub admin_api_key: String, - #[cfg(not(feature = "aws_kms"))] - pub recon_admin_api_key: String, - pub master_enc_key: Password, - #[cfg(feature = "aws_kms")] - pub kms_encrypted_jwt_secret: aws_kms::core::AwsKmsValue, - #[cfg(feature = "aws_kms")] - pub kms_encrypted_admin_api_key: aws_kms::core::AwsKmsValue, - #[cfg(feature = "aws_kms")] - pub kms_encrypted_recon_admin_api_key: aws_kms::core::AwsKmsValue, + pub jwt_secret: Secret<String>, + pub admin_api_key: Secret<String>, + pub recon_admin_api_key: Secret<String>, + pub master_enc_key: Secret<String>, } #[derive(Debug, Deserialize, Clone)] @@ -422,10 +395,10 @@ pub struct EphemeralConfig { #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Jwekey { - pub vault_encryption_key: String, - pub rust_locker_encryption_key: String, - pub vault_private_key: String, - pub tunnel_private_key: String, + pub vault_encryption_key: Secret<String>, + pub rust_locker_encryption_key: Secret<String>, + pub vault_private_key: Secret<String>, + pub tunnel_private_key: Secret<String>, } #[derive(Debug, Deserialize, Clone)] @@ -451,7 +424,7 @@ pub struct Server { #[serde(default)] pub struct Database { pub username: String, - pub password: Password, + pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, @@ -462,7 +435,6 @@ pub struct Database { pub max_lifetime: Option<u64>, } -#[cfg(not(feature = "aws_kms"))] impl From<Database> for storage_impl::config::Database { fn from(val: Database) -> Self { Self { @@ -615,15 +587,9 @@ pub struct WebhookIgnoreErrorSettings { #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct ApiKeys { - /// Base64-encoded (KMS encrypted) ciphertext of the key used for calculating hashes of API - /// keys - #[cfg(feature = "aws_kms")] - pub kms_encrypted_hash_key: aws_kms::core::AwsKmsValue, - /// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating /// hashes of API keys - #[cfg(not(feature = "aws_kms"))] - pub hash_key: String, + pub hash_key: Secret<String>, // Specifies the number of days before API key expiry when email reminders should be sent #[cfg(feature = "email")] @@ -644,10 +610,10 @@ pub struct WebhookSourceVerificationCall { #[derive(Debug, Deserialize, Clone, Default)] pub struct ApplePayDecryptConifg { - pub apple_pay_ppc: String, - pub apple_pay_ppc_key: String, - pub apple_pay_merchant_cert: String, - pub apple_pay_merchant_cert_key: String, + pub apple_pay_ppc: Secret<String>, + pub apple_pay_ppc_key: Secret<String>, + pub apple_pay_merchant_cert: Secret<String>, + pub apple_pay_merchant_cert_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] @@ -655,7 +621,7 @@ pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>, } -impl Settings { +impl Settings<SecuredSecret> { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) } @@ -702,9 +668,9 @@ impl Settings { pub fn validate(&self) -> ApplicationResult<()> { self.server.validate()?; - self.master_database.validate()?; + self.master_database.get_inner().validate()?; #[cfg(feature = "olap")] - self.replica_database.validate()?; + self.replica_database.get_inner().validate()?; self.redis.validate().map_err(|error| { println!("{error}"); ApplicationError::InvalidConfigurationValueError("Redis configuration".into()) @@ -722,7 +688,7 @@ impl Settings { )); } } - self.secrets.validate()?; + self.secrets.get_inner().validate()?; self.locker.validate()?; self.connectors.validate("connectors")?; @@ -734,11 +700,7 @@ impl Settings { .transpose()?; #[cfg(feature = "kv_store")] self.drainer.validate()?; - self.api_keys.validate()?; - #[cfg(feature = "aws_kms")] - self.kms - .validate() - .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; + self.api_keys.get_inner().validate()?; self.file_storage .validate() @@ -802,9 +764,9 @@ pub struct ConnectorOnboarding { #[cfg(feature = "olap")] #[derive(Debug, Deserialize, Clone, Default)] pub struct PayPalOnboarding { - pub client_id: masking::Secret<String>, - pub client_secret: masking::Secret<String>, - pub partner_id: masking::Secret<String>, + pub client_id: Secret<String>, + pub client_secret: Secret<String>, + pub partner_id: Secret<String>, pub enabled: bool, } diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 851b7ba7571..f3118cf840e 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -1,42 +1,23 @@ use common_utils::ext_traits::ConfigExt; +use masking::PeekInterface; use storage_impl::errors::ApplicationError; impl super::settings::Secrets { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; - #[cfg(not(feature = "aws_kms"))] - { - when(self.jwt_secret.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "JWT secret must not be empty".into(), - )) - })?; + when(self.jwt_secret.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "JWT secret must not be empty".into(), + )) + })?; - when(self.admin_api_key.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "admin API key must not be empty".into(), - )) - })?; - } + when(self.admin_api_key.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "admin API key must not be empty".into(), + )) + })?; - #[cfg(feature = "aws_kms")] - { - when(self.kms_encrypted_jwt_secret.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "KMS encrypted JWT secret must not be empty".into(), - )) - })?; - - when( - self.kms_encrypted_admin_api_key.is_default_or_empty(), - || { - Err(ApplicationError::InvalidConfigurationValueError( - "KMS encrypted admin API key must not be empty".into(), - )) - }, - )?; - } when(self.master_enc_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Master encryption key must not be empty".into(), @@ -155,15 +136,7 @@ impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; - #[cfg(feature = "aws_kms")] - when(self.kms_encrypted_hash_key.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "API key hashing key must not be empty when KMS feature is enabled".into(), - )) - })?; - - #[cfg(not(feature = "aws_kms"))] - when(self.hash_key.is_empty(), || { + when(self.hash_key.peek().is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty".into(), )) diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rs index 1a48b6e0e2c..6c10f95ea79 100644 --- a/crates/router/src/connection.rs +++ b/crates/router/src/connection.rs @@ -15,7 +15,7 @@ pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>; /// Panics if failed to create a redis pool #[allow(clippy::expect_used)] pub async fn redis_connection( - conf: &crate::configs::settings::Settings, + conf: &crate::configs::Settings, ) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(&conf.redis) .await diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 58f95e1371e..50bae175f64 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -35,7 +35,7 @@ pub mod user; #[cfg(feature = "olap")] pub mod user_role; pub mod utils; -#[cfg(all(feature = "olap", feature = "aws_kms"))] +#[cfg(feature = "olap")] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index b3f8931cde5..7d2069618d5 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -2,12 +2,6 @@ use common_utils::date_time; #[cfg(feature = "email")] use diesel_models::{api_keys::ApiKey, enums as storage_enums}; use error_stack::{report, IntoReport, ResultExt}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(not(feature = "aws_kms"))] -use masking::ExposeInterface; use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; @@ -29,49 +23,16 @@ const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY"; const API_KEY_EXPIRY_RUNNER: diesel_models::ProcessTrackerRunner = diesel_models::ProcessTrackerRunner::ApiKeyExpiryWorkflow; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms::decrypt::AwsKmsDecrypt; - -static HASH_KEY: tokio::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> = - tokio::sync::OnceCell::const_new(); - -pub async fn get_hash_key( - api_key_config: &settings::ApiKeys, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, - #[cfg(feature = "hashicorp-vault")] - hc_client: &external_services::hashicorp_vault::core::HashiCorpVault, -) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> { - HASH_KEY - .get_or_try_init(|| async { - let hash_key = { - #[cfg(feature = "aws_kms")] - { - api_key_config.kms_encrypted_hash_key.clone() - } - #[cfg(not(feature = "aws_kms"))] - { - masking::Secret::<_, masking::WithType>::new(api_key_config.hash_key.clone()) - } - }; - - #[cfg(feature = "hashicorp-vault")] - let hash_key = hash_key - .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - #[cfg(feature = "aws_kms")] - let hash_key = hash_key - .decrypt_inner(aws_kms_client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to AWS KMS decrypt API key hashing key")?; - - #[cfg(not(feature = "aws_kms"))] - let hash_key = hash_key.expose(); +static HASH_KEY: once_cell::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> = + once_cell::sync::OnceCell::new(); +impl settings::ApiKeys { + pub fn get_hash_key( + &self, + ) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> { + HASH_KEY.get_or_try_init(|| { <[u8; PlaintextApiKey::HASH_KEY_LEN]>::try_from( - hex::decode(hash_key) + hex::decode(self.hash_key.peek()) .into_report() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("API key hash key has invalid hexadecimal data")? @@ -82,7 +43,7 @@ pub async fn get_hash_key( .attach_printable("The API hashing key has incorrect length") .map(StrongSecret::new) }) - .await + } } // Defining new types `PlaintextApiKey` and `HashedApiKey` in the hopes of reducing the possibility @@ -152,13 +113,10 @@ impl PlaintextApiKey { #[instrument(skip_all)] pub async fn create_api_key( state: AppState, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, - #[cfg(feature = "hashicorp-vault")] - hc_client: &external_services::hashicorp_vault::core::HashiCorpVault, api_key: api::CreateApiKeyRequest, merchant_id: String, ) -> RouterResponse<api::CreateApiKeyResponse> { - let api_key_config = &state.conf.api_keys; + let api_key_config = state.conf.api_keys.get_inner(); let store = state.store.as_ref(); // We are not fetching merchant account as the merchant key store is needed to search for a // merchant account. @@ -172,14 +130,7 @@ pub async fn create_api_key( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let hash_key = get_hash_key( - api_key_config, - #[cfg(feature = "aws_kms")] - aws_kms_client, - #[cfg(feature = "hashicorp-vault")] - hc_client, - ) - .await?; + let hash_key = api_key_config.get_hash_key()?; let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); let api_key = storage::ApiKeyNew { key_id: PlaintextApiKey::new_key_id(), @@ -210,7 +161,7 @@ pub async fn create_api_key( #[cfg(feature = "email")] { if api_key.expires_at.is_some() { - let expiry_reminder_days = state.conf.api_keys.expiry_reminder_days.clone(); + let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone(); add_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await @@ -330,7 +281,7 @@ pub async fn update_api_key( #[cfg(feature = "email")] { - let expiry_reminder_days = state.conf.api_keys.expiry_reminder_days.clone(); + let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone(); let task_id = generate_task_id_for_api_key_expiry_workflow(&key_id); // In order to determine how to update the existing process in the process_tracker table, @@ -575,17 +526,7 @@ mod tests { let settings = settings::Settings::new().expect("invalid settings"); let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); - let hash_key = get_hash_key( - &settings.api_keys, - #[cfg(feature = "aws_kms")] - external_services::aws_kms::core::get_aws_kms_client(&settings.kms).await, - #[cfg(feature = "hashicorp-vault")] - external_services::hashicorp_vault::core::get_hashicorp_client(&settings.hc_vault) - .await - .unwrap(), - ) - .await - .unwrap(); + let hash_key = settings.api_keys.get_inner().get_hash_key().unwrap(); let hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek()); assert_ne!( diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rs index f4122a6a651..6d6834f0b6c 100644 --- a/crates/router/src/core/blocklist/transformers.rs +++ b/crates/router/src/core/blocklist/transformers.rs @@ -5,9 +5,7 @@ use common_utils::{ }; use error_stack::ResultExt; use josekit::jwe; -#[cfg(feature = "aws_kms")] -use masking::PeekInterface; -use masking::StrongSecret; +use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; use crate::{ @@ -35,8 +33,7 @@ impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse { } async fn generate_fingerprint_request<'a>( - #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + jwekey: &settings::Jwekey, locker: &settings::Locker, payload: &blocklist::GenerateFingerprintRequest, locker_choice: api_enums::LockerChoice, @@ -45,11 +42,7 @@ async fn generate_fingerprint_request<'a>( .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "aws_kms")] - let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - - #[cfg(not(feature = "aws_kms"))] - let private_key = jwekey.vault_private_key.as_bytes(); + let private_key = jwekey.vault_private_key.peek().as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) .await @@ -67,8 +60,7 @@ async fn generate_fingerprint_request<'a>( } async fn generate_jwe_payload_for_request( - #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, - #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + jwekey: &settings::Jwekey, jws: &str, locker_choice: api_enums::LockerChoice, ) -> CustomResult<encryption::JweBody, errors::VaultError> { @@ -89,18 +81,12 @@ async fn generate_jwe_payload_for_request( .encode_to_vec() .change_context(errors::VaultError::GenerateFingerprintFailed)?; - #[cfg(feature = "aws_kms")] let public_key = match locker_choice { api_enums::LockerChoice::HyperswitchCardVault => { - jwekey.jwekey.peek().vault_encryption_key.as_bytes() + jwekey.vault_encryption_key.peek().as_bytes() } }; - #[cfg(not(feature = "aws_kms"))] - let public_key = match locker_choice { - api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(), - }; - let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key) .await .change_context(errors::VaultError::SaveCardFailed) @@ -148,10 +134,7 @@ async fn call_to_locker_for_fingerprint( locker_choice: api_enums::LockerChoice, ) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "aws_kms"))] - let jwekey = &state.conf.jwekey; - #[cfg(feature = "aws_kms")] - let jwekey = &state.kms_secrets; + let jwekey = state.conf.jwekey.get_inner(); let request = generate_fingerprint_request(jwekey, locker, payload, locker_choice).await?; let response = services::call_connector_api(state, request) @@ -175,30 +158,20 @@ async fn call_to_locker_for_fingerprint( } async fn decrypt_generate_fingerprint_response_payload( - #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + jwekey: &settings::Jwekey, + jwe_body: encryption::JweBody, locker_choice: Option<api_enums::LockerChoice>, ) -> CustomResult<String, errors::VaultError> { let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault); - #[cfg(feature = "aws_kms")] let public_key = match target_locker { api_enums::LockerChoice::HyperswitchCardVault => { - jwekey.jwekey.peek().vault_encryption_key.as_bytes() + jwekey.vault_encryption_key.peek().as_bytes() } }; - #[cfg(feature = "aws_kms")] - let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - - #[cfg(not(feature = "aws_kms"))] - let public_key = match target_locker { - api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(), - }; - - #[cfg(not(feature = "aws_kms"))] - let private_key = jwekey.vault_private_key.as_bytes(); + let private_key = jwekey.vault_private_key.peek().as_bytes(); let jwt = payment_methods::get_dotted_jwe(jwe_body); let alg = jwe::RSA_OAEP; diff --git a/crates/router/src/core/connector_onboarding.rs b/crates/router/src/core/connector_onboarding.rs index e6c1fc9d378..21377d0ba0b 100644 --- a/crates/router/src/core/connector_onboarding.rs +++ b/crates/router/src/core/connector_onboarding.rs @@ -24,8 +24,8 @@ pub async fn get_action_url( utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) .await?; - let connector_onboarding_conf = state.conf.connector_onboarding.clone(); - let is_enabled = utils::is_enabled(request.connector, &connector_onboarding_conf); + let connector_onboarding_conf = state.conf.connector_onboarding.get_inner(); + let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf); let tracking_id = utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector) .await?; @@ -58,8 +58,8 @@ pub async fn sync_onboarding_status( utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) .await?; - let connector_onboarding_conf = state.conf.connector_onboarding.clone(); - let is_enabled = utils::is_enabled(request.connector, &connector_onboarding_conf); + let connector_onboarding_conf = state.conf.connector_onboarding.get_inner(); + let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf); let tracking_id = utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector) .await?; @@ -75,10 +75,10 @@ pub async fn sync_onboarding_status( ref paypal_onboarding_data, )) = status { - let connector_onboarding_conf = state.conf.connector_onboarding.clone(); + let connector_onboarding_conf = state.conf.connector_onboarding.get_inner(); let auth_details = oss_types::ConnectorAuthType::SignatureKey { - api_key: connector_onboarding_conf.paypal.client_secret, - key1: connector_onboarding_conf.paypal.client_id, + api_key: connector_onboarding_conf.paypal.client_secret.clone(), + key1: connector_onboarding_conf.paypal.client_id.clone(), api_secret: Secret::new(paypal_onboarding_data.payer_id.clone()), }; let update_mca_data = paypal::update_mca( diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs index 644a2220aee..4c1f16e9135 100644 --- a/crates/router/src/core/connector_onboarding/paypal.rs +++ b/crates/router/src/core/connector_onboarding/paypal.rs @@ -63,7 +63,13 @@ pub async fn get_action_url_from_paypal( } fn merchant_onboarding_status_url(state: AppState, tracking_id: String) -> String { - let partner_id = state.conf.connector_onboarding.paypal.partner_id.to_owned(); + let partner_id = state + .conf + .connector_onboarding + .get_inner() + .paypal + .partner_id + .to_owned(); format!( "{}v1/customer/partners/{}/merchant-integrations?tracking_id={}", state.conf.connectors.paypal.base_url, diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs index b0d06f9fd65..f2791deb7b6 100644 --- a/crates/router/src/core/currency.rs +++ b/crates/router/src/core/currency.rs @@ -11,16 +11,13 @@ use crate::{ pub async fn retrieve_forex( state: AppState, ) -> CustomResult<ApplicationResponse<currency::FxExchangeRatesCacheEntry>, ApiErrorResponse> { + let forex_api = state.conf.forex_api.get_inner(); Ok(ApplicationResponse::Json( get_forex_rates( &state, - state.conf.forex_api.call_delay, - state.conf.forex_api.local_fetch_retry_delay, - state.conf.forex_api.local_fetch_retry_count, - #[cfg(feature = "aws_kms")] - &state.conf.kms, - #[cfg(feature = "hashicorp-vault")] - &state.conf.hc_vault, + forex_api.call_delay, + forex_api.local_fetch_retry_delay, + forex_api.local_fetch_retry_count, ) .await .change_context(ApiErrorResponse::GenericNotFoundError { @@ -44,10 +41,6 @@ pub async fn convert_forex( amount, to_currency, from_currency, - #[cfg(feature = "aws_kms")] - &state.conf.kms, - #[cfg(feature = "hashicorp-vault")] - &state.conf.hc_vault, )) .await .change_context(ApiErrorResponse::InternalServerError)?, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 9ebcc61fce3..882d384edd4 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -653,10 +653,7 @@ pub async fn get_payment_method_from_hs_locker<'a>( locker_choice: Option<api_enums::LockerChoice>, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "aws_kms"))] - let jwekey = &state.conf.jwekey; - #[cfg(feature = "aws_kms")] - let jwekey = &state.kms_secrets; + let jwekey = state.conf.jwekey.get_inner(); let payment_method_data = if !locker.mock_locker { let request = payment_methods::mk_get_card_request_hs( @@ -716,10 +713,7 @@ pub async fn call_to_locker_hs<'a>( locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "aws_kms"))] - let jwekey = &state.conf.jwekey; - #[cfg(feature = "aws_kms")] - let jwekey = &state.kms_secrets; + let jwekey = state.conf.jwekey.get_inner(); let db = &*state.store; let stored_card_response = if !locker.mock_locker { let request = @@ -777,10 +771,7 @@ pub async fn get_card_from_hs_locker<'a>( locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<payment_methods::Card, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "aws_kms"))] - let jwekey = &state.conf.jwekey; - #[cfg(feature = "aws_kms")] - let jwekey = &state.kms_secrets; + let jwekey = &state.conf.jwekey.get_inner(); if !locker.mock_locker { let request = payment_methods::mk_get_card_request_hs( @@ -832,10 +823,7 @@ pub async fn delete_card_from_hs_locker<'a>( card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { let locker = &state.conf.locker; - #[cfg(not(feature = "aws_kms"))] - let jwekey = &state.conf.jwekey; - #[cfg(feature = "aws_kms")] - let jwekey = &state.kms_secrets; + let jwekey = &state.conf.jwekey.get_inner(); let request = payment_methods::mk_delete_card_request_hs( jwekey, @@ -1445,7 +1433,7 @@ pub async fn list_payment_methods( } let pm_auth_key = format!("pm_auth_{}", payment_intent.payment_id); - let redis_expiry = state.conf.payment_method_auth.redis_expiry; + let redis_expiry = state.conf.payment_method_auth.get_inner().redis_expiry; if let Some(rc) = redis_conn { rc.serialize_and_set_key_with_expiry(pm_auth_key.as_str(), val, redis_expiry) diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 57e46bc9769..ea25c73499e 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -197,30 +197,19 @@ pub fn get_dotted_jws(jws: encryption::JwsBody) -> String { } pub async fn get_decrypted_response_payload( - #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + jwekey: &settings::Jwekey, jwe_body: encryption::JweBody, locker_choice: Option<api_enums::LockerChoice>, ) -> CustomResult<String, errors::VaultError> { let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault); - #[cfg(feature = "aws_kms")] let public_key = match target_locker { api_enums::LockerChoice::HyperswitchCardVault => { - jwekey.jwekey.peek().vault_encryption_key.as_bytes() + jwekey.vault_encryption_key.peek().as_bytes() } }; - #[cfg(feature = "aws_kms")] - let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - - #[cfg(not(feature = "aws_kms"))] - let public_key = match target_locker { - api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(), - }; - - #[cfg(not(feature = "aws_kms"))] - let private_key = jwekey.vault_private_key.as_bytes(); + let private_key = jwekey.vault_private_key.peek().as_bytes(); let jwt = get_dotted_jwe(jwe_body); let alg = jwe::RSA_OAEP; @@ -246,8 +235,7 @@ pub async fn get_decrypted_response_payload( } pub async fn mk_basilisk_req( - #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, - #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + jwekey: &settings::Jwekey, jws: &str, locker_choice: api_enums::LockerChoice, ) -> CustomResult<encryption::JweBody, errors::VaultError> { @@ -267,18 +255,12 @@ pub async fn mk_basilisk_req( .encode_to_vec() .change_context(errors::VaultError::SaveCardFailed)?; - #[cfg(feature = "aws_kms")] let public_key = match locker_choice { api_enums::LockerChoice::HyperswitchCardVault => { - jwekey.jwekey.peek().vault_encryption_key.as_bytes() + jwekey.vault_encryption_key.peek().as_bytes() } }; - #[cfg(not(feature = "aws_kms"))] - let public_key = match locker_choice { - api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(), - }; - let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key) .await .change_context(errors::VaultError::SaveCardFailed) @@ -301,8 +283,7 @@ pub async fn mk_basilisk_req( } pub async fn mk_add_locker_request_hs<'a>( - #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + jwekey: &settings::Jwekey, locker: &settings::Locker, payload: &StoreLockerReq<'a>, locker_choice: api_enums::LockerChoice, @@ -311,11 +292,7 @@ pub async fn mk_add_locker_request_hs<'a>( .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "aws_kms")] - let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - - #[cfg(not(feature = "aws_kms"))] - let private_key = jwekey.vault_private_key.as_bytes(); + let private_key = jwekey.vault_private_key.peek().as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) .await @@ -471,8 +448,7 @@ pub fn mk_add_card_request( } pub async fn mk_get_card_request_hs( - #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + jwekey: &settings::Jwekey, locker: &settings::Locker, customer_id: &str, merchant_id: &str, @@ -489,11 +465,7 @@ pub async fn mk_get_card_request_hs( .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "aws_kms")] - let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - - #[cfg(not(feature = "aws_kms"))] - let private_key = jwekey.vault_private_key.as_bytes(); + let private_key = jwekey.vault_private_key.peek().as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) .await @@ -548,8 +520,7 @@ pub fn mk_get_card_response(card: GetCardResponse) -> errors::RouterResult<Card> } pub async fn mk_delete_card_request_hs( - #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, - #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + jwekey: &settings::Jwekey, locker: &settings::Locker, customer_id: &str, merchant_id: &str, @@ -565,11 +536,7 @@ pub async fn mk_delete_card_request_hs( .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "aws_kms")] - let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - - #[cfg(not(feature = "aws_kms"))] - let private_key = jwekey.vault_private_key.as_bytes(); + let private_key = jwekey.vault_private_key.peek().as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) .await diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 479a0685a97..e29b66ea0ca 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -2,13 +2,6 @@ use api_models::payments as payment_types; use async_trait::async_trait; use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::{IntoReport, Report, ResultExt}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "hashicorp-vault")] use masking::ExposeInterface; use super::{ConstructFlowSpecificData, Feature}; @@ -183,130 +176,40 @@ async fn create_applepay_session_token( payment_request_data, session_token_data, } => { - let ( - apple_pay_merchant_cert, - apple_pay_merchant_cert_key, - common_merchant_identifier, - ) = async { - #[cfg(feature = "hashicorp-vault")] - let client = - external_services::hashicorp_vault::core::get_hashicorp_client( - &state.conf.hc_vault, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while building hashicorp client")?; - - #[cfg(feature = "hashicorp-vault")] - { - Ok::<_, Report<errors::ApiErrorResponse>>(( - masking::Secret::new( - state - .conf - .applepay_decrypt_keys - .apple_pay_merchant_cert - .clone(), - ) - .fetch_inner::<hashicorp_vault::core::Kv2>(client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)? - .expose(), - masking::Secret::new( - state - .conf - .applepay_decrypt_keys - .apple_pay_merchant_cert_key - .clone(), - ) - .fetch_inner::<hashicorp_vault::core::Kv2>(client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)? - .expose(), - masking::Secret::new( - state - .conf - .applepay_merchant_configs - .common_merchant_identifier - .clone(), - ) - .fetch_inner::<hashicorp_vault::core::Kv2>(client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)? - .expose(), - )) - } - - #[cfg(not(feature = "hashicorp-vault"))] - { - Ok::<_, Report<errors::ApiErrorResponse>>(( - state - .conf - .applepay_decrypt_keys - .apple_pay_merchant_cert - .clone(), - state - .conf - .applepay_decrypt_keys - .apple_pay_merchant_cert_key - .clone(), - state - .conf - .applepay_merchant_configs - .common_merchant_identifier - .clone(), - )) - } - } - .await?; - - #[cfg(feature = "aws_kms")] - let decrypted_apple_pay_merchant_cert = - aws_kms::core::get_aws_kms_client(&state.conf.kms) - .await - .decrypt(apple_pay_merchant_cert) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Apple pay merchant certificate decryption failed")?; - - #[cfg(feature = "aws_kms")] - let decrypted_apple_pay_merchant_cert_key = - aws_kms::core::get_aws_kms_client(&state.conf.kms) - .await - .decrypt(apple_pay_merchant_cert_key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "Apple pay merchant certificate key decryption failed", - )?; - - #[cfg(feature = "aws_kms")] - let decrypted_merchant_identifier = - aws_kms::core::get_aws_kms_client(&state.conf.kms) - .await - .decrypt(common_merchant_identifier) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Apple pay merchant identifier decryption failed")?; - - #[cfg(not(feature = "aws_kms"))] - let decrypted_merchant_identifier = common_merchant_identifier; + let merchant_identifier = state + .conf + .applepay_merchant_configs + .get_inner() + .common_merchant_identifier + .clone() + .expose(); let apple_pay_session_request = get_session_request_for_simplified_apple_pay( - decrypted_merchant_identifier.to_string(), + merchant_identifier, session_token_data, ); - #[cfg(not(feature = "aws_kms"))] - let decrypted_apple_pay_merchant_cert = apple_pay_merchant_cert; - - #[cfg(not(feature = "aws_kms"))] - let decrypted_apple_pay_merchant_cert_key = apple_pay_merchant_cert_key; + let apple_pay_merchant_cert = state + .conf + .applepay_decrypt_keys + .get_inner() + .apple_pay_merchant_cert + .clone() + .expose(); + + let apple_pay_merchant_cert_key = state + .conf + .applepay_decrypt_keys + .get_inner() + .apple_pay_merchant_cert_key + .clone() + .expose(); ( payment_request_data, apple_pay_session_request, - decrypted_apple_pay_merchant_cert.to_owned(), - decrypted_apple_pay_merchant_cert_key.to_owned(), + apple_pay_merchant_cert, + apple_pay_merchant_cert_key, ) } payment_types::ApplePayCombinedMetadata::Manual { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index b6e28faa4eb..0eaf3c07ee6 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -13,12 +13,6 @@ use data_models::{ use diesel_models::enums; // TODO : Evaluate all the helper functions () use error_stack::{report, IntoReport, ResultExt}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::decrypt::VaultFetch; use josekit::jwe; use masking::{ExposeInterface, PeekInterface}; use openssl::{ @@ -2903,17 +2897,14 @@ pub async fn get_merchant_connector_account( }, )?; - #[cfg(feature = "aws_kms")] let private_key = state - .kms_secrets + .conf .jwekey - .peek() + .get_inner() .tunnel_private_key + .peek() .as_bytes(); - #[cfg(not(feature = "aws_kms"))] - let private_key = state.conf.jwekey.tunnel_private_key.as_bytes(); - let decrypted_mca = services::decrypt_jwe(mca_config.config.as_str(), services::KeyIdCheck::SkipKeyIdCheck, private_key, jwe::RSA_OAEP_256) .await .change_context(errors::ApiErrorResponse::UnprocessableEntity{ @@ -3550,39 +3541,13 @@ impl ApplePayData { &self, state: &AppState, ) -> CustomResult<String, errors::ApplePayDecryptionError> { - let apple_pay_ppc = async { - #[cfg(feature = "hashicorp-vault")] - let client = external_services::hashicorp_vault::core::get_hashicorp_client( - &state.conf.hc_vault, - ) - .await - .change_context(errors::ApplePayDecryptionError::DecryptionFailed) - .attach_printable("Failed while creating client")?; - - #[cfg(feature = "hashicorp-vault")] - let output = - masking::Secret::new(state.conf.applepay_decrypt_keys.apple_pay_ppc.clone()) - .fetch_inner::<hashicorp_vault::core::Kv2>(client) - .await - .change_context(errors::ApplePayDecryptionError::DecryptionFailed)? - .expose(); - - #[cfg(not(feature = "hashicorp-vault"))] - let output = state.conf.applepay_decrypt_keys.apple_pay_ppc.clone(); - - Ok::<_, error_stack::Report<errors::ApplePayDecryptionError>>(output) - } - .await?; - - #[cfg(feature = "aws_kms")] - let cert_data = aws_kms::core::get_aws_kms_client(&state.conf.kms) - .await - .decrypt(&apple_pay_ppc) - .await - .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; - - #[cfg(not(feature = "aws_kms"))] - let cert_data = &apple_pay_ppc; + let cert_data = state + .conf + .applepay_decrypt_keys + .get_inner() + .apple_pay_ppc + .clone() + .expose(); let base64_decode_cert_data = BASE64_ENGINE .decode(cert_data) @@ -3634,40 +3599,14 @@ impl ApplePayData { .change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed) .attach_printable("Failed to deserialize the public key")?; - let apple_pay_ppc_key = async { - #[cfg(feature = "hashicorp-vault")] - let client = external_services::hashicorp_vault::core::get_hashicorp_client( - &state.conf.hc_vault, - ) - .await - .change_context(errors::ApplePayDecryptionError::DecryptionFailed) - .attach_printable("Failed while creating client")?; - - #[cfg(feature = "hashicorp-vault")] - let output = - masking::Secret::new(state.conf.applepay_decrypt_keys.apple_pay_ppc_key.clone()) - .fetch_inner::<hashicorp_vault::core::Kv2>(client) - .await - .change_context(errors::ApplePayDecryptionError::DecryptionFailed) - .attach_printable("Failed while creating client")? - .expose(); - - #[cfg(not(feature = "hashicorp-vault"))] - let output = state.conf.applepay_decrypt_keys.apple_pay_ppc_key.clone(); - - Ok::<_, error_stack::Report<errors::ApplePayDecryptionError>>(output) - } - .await?; - - #[cfg(feature = "aws_kms")] - let decrypted_apple_pay_ppc_key = aws_kms::core::get_aws_kms_client(&state.conf.kms) - .await - .decrypt(&apple_pay_ppc_key) - .await - .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; + let decrypted_apple_pay_ppc_key = state + .conf + .applepay_decrypt_keys + .get_inner() + .apple_pay_ppc_key + .clone() + .expose(); - #[cfg(not(feature = "aws_kms"))] - let decrypted_apple_pay_ppc_key = &apple_pay_ppc_key; // Create PKey objects from EcKey let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes()) .into_report() diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index f00c452f3ea..982ed9cae94 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -5,8 +5,6 @@ use api_models::{ payment_methods::{self, BankAccountAccessCreds}, payments::{AddressDetails, BankDebitBilling, BankDebitData, PaymentMethodData}, }; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::{self, decrypt::VaultFetch}; use hex; pub mod helpers; pub mod transformers; @@ -19,8 +17,6 @@ use common_utils::{ }; use data_models::payments::PaymentIntent; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "aws_kms")] -pub use external_services::aws_kms; use helpers::PaymentAuthConnectorDataExt; use masking::{ExposeInterface, PeekInterface}; use pm_auth::{ @@ -347,34 +343,13 @@ async fn store_bank_details_in_payment_methods( } } - let pm_auth_key = async { - #[cfg(feature = "hashicorp-vault")] - let client = - external_services::hashicorp_vault::core::get_hashicorp_client(&state.conf.hc_vault) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed while creating client")?; - - #[cfg(feature = "hashicorp-vault")] - let output = masking::Secret::new(state.conf.payment_method_auth.pm_auth_key.clone()) - .fetch_inner::<hashicorp_vault::core::Kv2>(client) - .await - .change_context(ApiErrorResponse::InternalServerError)? - .expose(); - - #[cfg(not(feature = "hashicorp-vault"))] - let output = state.conf.payment_method_auth.pm_auth_key.clone(); - - Ok::<_, error_stack::Report<ApiErrorResponse>>(output) - } - .await?; - - #[cfg(feature = "aws_kms")] - let pm_auth_key = aws_kms::core::get_aws_kms_client(&state.conf.kms) - .await - .decrypt(pm_auth_key) - .await - .change_context(ApiErrorResponse::InternalServerError)?; + let pm_auth_key = state + .conf + .payment_method_auth + .get_inner() + .pm_auth_key + .clone() + .expose(); let mut update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)> = Vec::new(); diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index ff51668ec57..d749163aa28 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -15,7 +15,7 @@ use super::payouts::PayoutData; #[cfg(feature = "payouts")] use crate::core::payments; use crate::{ - configs::settings, + configs::Settings, consts, core::errors::{self, RouterResult, StorageErrorExt}, db::StorageInterface, @@ -942,7 +942,7 @@ pub async fn construct_retrieve_file_router_data<'a>( } pub fn is_merchant_enabled_for_payment_id_as_connector_request_id( - conf: &settings::Settings, + conf: &Settings, merchant_id: &str, ) -> bool { let config_map = &conf @@ -952,7 +952,7 @@ pub fn is_merchant_enabled_for_payment_id_as_connector_request_id( } pub fn get_connector_request_reference_id( - conf: &settings::Settings, + conf: &Settings, merchant_id: &str, payment_attempt: &data_models::payments::payment_attempt::PaymentAttempt, ) -> String { diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index 79513bfb308..04ccdc32f2c 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -2,8 +2,7 @@ pub mod utils; use api_models::verifications::{self, ApplepayMerchantResponse}; use common_utils::{errors::CustomResult, request::RequestContent}; use error_stack::ResultExt; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; +use masking::ExposeInterface; use crate::{core::errors::api_error_response, headers, logger, routes::AppState, services}; @@ -11,44 +10,26 @@ const APPLEPAY_INTERNAL_MERCHANT_NAME: &str = "Applepay_merchant"; pub async fn verify_merchant_creds_for_applepay( state: AppState, - _req: &actix_web::HttpRequest, body: verifications::ApplepayMerchantVerificationRequest, - kms_config: &aws_kms::core::AwsKmsConfig, merchant_id: String, ) -> CustomResult< services::ApplicationResponse<ApplepayMerchantResponse>, api_error_response::ApiErrorResponse, > { - let encrypted_merchant_identifier = &state - .conf - .applepay_merchant_configs - .common_merchant_identifier; - let encrypted_cert = &state.conf.applepay_merchant_configs.merchant_cert; - let encrypted_key = &state.conf.applepay_merchant_configs.merchant_cert_key; - let applepay_endpoint = &state.conf.applepay_merchant_configs.applepay_endpoint; + let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner(); - let applepay_internal_merchant_identifier = aws_kms::core::get_aws_kms_client(kms_config) - .await - .decrypt(encrypted_merchant_identifier) - .await - .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; - - let cert_data = aws_kms::core::get_aws_kms_client(kms_config) - .await - .decrypt(encrypted_cert) - .await - .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; - - let key_data = aws_kms::core::get_aws_kms_client(kms_config) - .await - .decrypt(encrypted_key) - .await - .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; + let applepay_internal_merchant_identifier = applepay_merchant_configs + .common_merchant_identifier + .clone() + .expose(); + let cert_data = applepay_merchant_configs.merchant_cert.clone().expose(); + let key_data = applepay_merchant_configs.merchant_cert_key.clone().expose(); + let applepay_endpoint = &applepay_merchant_configs.applepay_endpoint; let request_body = verifications::ApplepayMerchantVerificationConfigs { domain_names: body.domain_names.clone(), - encrypt_to: applepay_internal_merchant_identifier.to_string(), - partner_internal_merchant_identifier: applepay_internal_merchant_identifier.to_string(), + encrypt_to: applepay_internal_merchant_identifier.clone(), + partner_internal_merchant_identifier: applepay_internal_merchant_identifier, partner_merchant_name: APPLEPAY_INTERNAL_MERCHANT_NAME.to_string(), }; diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 5b5bc414d2c..97d981c68eb 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -30,6 +30,7 @@ use actix_web::{ middleware::ErrorHandlers, }; use http::StatusCode; +use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret; use routes::AppState; use storage_impl::errors::ApplicationResult; use tokio::sync::{mpsc, oneshot}; @@ -141,7 +142,7 @@ pub fn mk_app( .service(routes::ConnectorOnboarding::server(state.clone())) } - #[cfg(all(feature = "olap", feature = "aws_kms"))] + #[cfg(feature = "olap")] { server_app = server_app.service(routes::Verify::server(state.clone())); } @@ -174,7 +175,7 @@ pub fn mk_app( /// /// Unwrap used because without the value we can't start the server #[allow(clippy::expect_used, clippy::unwrap_used)] -pub async fn start_server(conf: settings::Settings) -> ApplicationResult<Server> { +pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> ApplicationResult<Server> { logger::debug!(startup_config=?conf); let server = conf.server.clone(); let (tx, rx) = oneshot::channel(); diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 51c938b0971..0d7c903b06f 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -37,7 +37,7 @@ pub mod routing; pub mod user; #[cfg(feature = "olap")] pub mod user_role; -#[cfg(all(feature = "olap", feature = "aws_kms"))] +#[cfg(feature = "olap")] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; @@ -57,7 +57,7 @@ pub use self::app::Forex; pub use self::app::Payouts; #[cfg(all(feature = "olap", feature = "recon"))] pub use self::app::Recon; -#[cfg(all(feature = "olap", feature = "aws_kms"))] +#[cfg(feature = "olap")] pub use self::app::Verify; pub use self::app::{ ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, ConnectorOnboarding, Customers, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index cf0f009a0b1..2e95fd536cf 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -1,6 +1,4 @@ use actix_web::{web, HttpRequest, Responder}; -#[cfg(feature = "hashicorp-vault")] -use error_stack::ResultExt; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -44,27 +42,7 @@ pub async fn api_key_create( &req, payload, |state, _, payload| async { - #[cfg(feature = "aws_kms")] - let aws_kms_client = - external_services::aws_kms::core::get_aws_kms_client(&state.clone().conf.kms).await; - - #[cfg(feature = "hashicorp-vault")] - let hc_client = external_services::hashicorp_vault::core::get_hashicorp_client( - &state.clone().conf.hc_vault, - ) - .await - .change_context(crate::core::errors::ApiErrorResponse::InternalServerError)?; - - api_keys::create_api_key( - state, - #[cfg(feature = "aws_kms")] - aws_kms_client, - #[cfg(feature = "hashicorp-vault")] - hc_client, - payload, - merchant_id.clone(), - ) - .await + api_keys::create_api_key(state, payload, merchant_id.clone()).await }, auth::auth_type( &auth::AdminApiAuth, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index e204ef3b9e0..73558c78d7b 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1,25 +1,17 @@ use std::sync::Arc; use actix_web::{web, Scope}; -#[cfg(all( - feature = "olap", - any(feature = "hashicorp-vault", feature = "aws_kms") -))] -use analytics::AnalyticsConfig; #[cfg(all(feature = "business_profile_routing", feature = "olap"))] use api_models::routing::RoutingRetrieveQuery; #[cfg(feature = "olap")] use common_enums::TransactionType; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "email")] use external_services::email::{ses::AwsSes, EmailService}; use external_services::file_storage::FileStorageInterface; -#[cfg(all(feature = "olap", feature = "hashicorp-vault"))] -use external_services::hashicorp_vault::decrypt::VaultFetch; -use hyperswitch_interfaces::encryption_interface::EncryptionManagementInterface; -#[cfg(all(feature = "olap", feature = "aws_kms"))] -use masking::PeekInterface; +use hyperswitch_interfaces::{ + encryption_interface::EncryptionManagementInterface, + secrets_interface::secret_state::{RawSecret, SecuredSecret}, +}; use router_env::tracing_actix_web::RequestId; use scheduler::SchedulerInterface; use storage_impl::MockDb; @@ -37,7 +29,7 @@ use super::payouts::*; use super::pm_auth; #[cfg(feature = "olap")] use super::routing as cloud_routing; -#[cfg(all(feature = "olap", feature = "aws_kms"))] +#[cfg(feature = "olap")] use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "olap")] use super::{ @@ -49,6 +41,7 @@ use super::{cache::*, health::*}; use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*}; #[cfg(feature = "oltp")] use super::{ephemeral_key::*, payment_methods::*, webhooks::*}; +use crate::configs::secrets_transformers; #[cfg(all(feature = "frm", feature = "oltp"))] use crate::routes::fraud_check as frm_routes; #[cfg(all(feature = "recon", feature = "olap"))] @@ -68,12 +61,10 @@ pub use crate::{ pub struct AppState { pub flow_name: String, pub store: Box<dyn StorageInterface>, - pub conf: Arc<settings::Settings>, + pub conf: Arc<settings::Settings<RawSecret>>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<dyn EmailService>, - #[cfg(feature = "aws_kms")] - pub kms_secrets: Arc<settings::ActiveKmsSecrets>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] pub pool: crate::analytics::AnalyticsProvider, @@ -89,7 +80,7 @@ impl scheduler::SchedulerAppState for AppState { } pub trait AppStateInfo { - fn conf(&self) -> settings::Settings; + fn conf(&self) -> settings::Settings<RawSecret>; fn store(&self) -> Box<dyn StorageInterface>; fn event_handler(&self) -> EventsHandler; #[cfg(feature = "email")] @@ -101,7 +92,7 @@ pub trait AppStateInfo { } impl AppStateInfo for AppState { - fn conf(&self) -> settings::Settings { + fn conf(&self) -> settings::Settings<RawSecret> { self.conf.as_ref().to_owned() } fn store(&self) -> Box<dyn StorageInterface> { @@ -138,7 +129,7 @@ impl AsRef<Self> for AppState { } #[cfg(feature = "email")] -pub async fn create_email_client(settings: &settings::Settings) -> impl EmailService { +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 @@ -151,12 +142,20 @@ impl AppState { /// /// Panics if Store can't be created or JWE decryption fails pub async fn with_storage( - #[cfg_attr(not(all(feature = "olap", feature = "aws_kms")), allow(unused_mut))] - mut conf: settings::Settings, + conf: settings::Settings<SecuredSecret>, storage_impl: StorageImpl, shut_down_signal: oneshot::Sender<()>, api_client: Box<dyn crate::services::ApiClient>, ) -> Self { + #[allow(clippy::expect_used)] + let secret_management_client = conf + .secrets_management + .get_secret_management_client() + .await + .expect("Failed to create secret management client"); + + let conf = secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await; + #[allow(clippy::expect_used)] let encryption_client = conf .encryption_management @@ -165,14 +164,6 @@ impl AppState { .expect("Failed to create encryption client"); Box::pin(async move { - #[cfg(feature = "aws_kms")] - let aws_kms_client = aws_kms::core::get_aws_kms_client(&conf.kms).await; - #[cfg(all(feature = "hashicorp-vault", feature = "olap"))] - #[allow(clippy::expect_used)] - let hc_client = - external_services::hashicorp_vault::core::get_hashicorp_client(&conf.hc_vault) - .await - .expect("Failed while creating hashicorp_client"); let testable = storage_impl == StorageImpl::PostgresqlTest; #[allow(clippy::expect_used)] let event_handler = conf @@ -208,80 +199,9 @@ impl AppState { ), }; - #[cfg(all(feature = "hashicorp-vault", feature = "olap"))] - #[allow(clippy::expect_used)] - match conf.analytics { - AnalyticsConfig::Clickhouse { .. } => {} - AnalyticsConfig::Sqlx { ref mut sqlx } - | AnalyticsConfig::CombinedCkh { ref mut sqlx, .. } - | AnalyticsConfig::CombinedSqlx { ref mut sqlx, .. } => { - sqlx.password = sqlx - .password - .clone() - .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) - .await - .expect("Failed while fetching from hashicorp vault"); - } - }; - - #[cfg(all(feature = "aws_kms", feature = "olap"))] - #[allow(clippy::expect_used)] - match conf.analytics { - AnalyticsConfig::Clickhouse { .. } => {} - AnalyticsConfig::Sqlx { ref mut sqlx } - | AnalyticsConfig::CombinedCkh { ref mut sqlx, .. } - | AnalyticsConfig::CombinedSqlx { ref mut sqlx, .. } => { - sqlx.password = aws_kms_client - .decrypt(&sqlx.password.peek()) - .await - .expect("Failed to decrypt password") - .into(); - } - }; - - #[cfg(all(feature = "hashicorp-vault", feature = "olap"))] - #[allow(clippy::expect_used)] - { - conf.connector_onboarding = conf - .connector_onboarding - .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) - .await - .expect("Failed to decrypt connector onboarding credentials"); - } - - #[cfg(all(feature = "aws_kms", feature = "olap"))] - #[allow(clippy::expect_used)] - { - conf.connector_onboarding = conf - .connector_onboarding - .decrypt_inner(aws_kms_client) - .await - .expect("Failed to decrypt connector onboarding credentials"); - } - #[cfg(feature = "olap")] let pool = crate::analytics::AnalyticsProvider::from_conf(&conf.analytics).await; - #[cfg(all(feature = "hashicorp-vault", feature = "olap"))] - #[allow(clippy::expect_used)] - { - conf.jwekey = conf - .jwekey - .clone() - .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) - .await - .expect("Failed to decrypt connector onboarding credentials"); - } - - #[cfg(feature = "aws_kms")] - #[allow(clippy::expect_used)] - let kms_secrets = settings::ActiveKmsSecrets { - jwekey: conf.jwekey.clone().into(), - } - .decrypt_inner(aws_kms_client) - .await - .expect("Failed while performing AWS KMS decryption"); - #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await); @@ -293,8 +213,6 @@ impl AppState { conf: Arc::new(conf), #[cfg(feature = "email")] email_client, - #[cfg(feature = "aws_kms")] - kms_secrets: Arc::new(kms_secrets), api_client, event_handler, #[cfg(feature = "olap")] @@ -308,7 +226,7 @@ impl AppState { } pub async fn new( - conf: settings::Settings, + conf: settings::Settings<SecuredSecret>, shut_down_signal: oneshot::Sender<()>, api_client: Box<dyn crate::services::ApiClient>, ) -> Self { @@ -1114,10 +1032,10 @@ impl Gsm { } } -#[cfg(all(feature = "olap", feature = "aws_kms"))] +#[cfg(feature = "olap")] pub struct Verify; -#[cfg(all(feature = "olap", feature = "aws_kms"))] +#[cfg(feature = "olap")] impl Verify { pub fn server(state: AppState) -> Scope { web::scope("/verify") diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 770ae9aafcc..f667479ceaa 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -5,10 +5,6 @@ global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses -#[cfg(feature = "aws_kms")] -counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures -#[cfg(feature = "aws_kms")] -counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures // API Level Metrics counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER); diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs index 4bcbacdf991..91fd204ba2f 100644 --- a/crates/router/src/routes/verification.rs +++ b/crates/router/src/routes/verification.rs @@ -17,7 +17,6 @@ pub async fn apple_pay_merchant_registration( ) -> impl Responder { let flow = Flow::Verification; let merchant_id = path.into_inner(); - let kms_conf = &state.clone().conf.kms; Box::pin(api::server_wrap( flow, state, @@ -26,9 +25,7 @@ pub async fn apple_pay_merchant_registration( |state, _, body| { verification::verify_merchant_creds_for_applepay( state.clone(), - &req, body, - kms_conf, merchant_id.clone(), ) }, diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index dc7bf14fecf..617b9df7122 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -13,22 +13,16 @@ pub mod recon; #[cfg(feature = "email")] pub mod email; -#[cfg(any(feature = "aws_kms", feature = "hashicorp-vault"))] -use data_models::errors::StorageError; use data_models::errors::StorageResult; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::decrypt::VaultFetch; -use masking::{PeekInterface, StrongSecret}; +use masking::{ExposeInterface, StrongSecret}; #[cfg(feature = "kv_store")] use storage_impl::KVRouterStore; use storage_impl::RouterStore; use tokio::sync::oneshot; pub use self::{api::*, encryption::*}; -use crate::{configs::settings, consts, core::errors}; +use crate::{configs::Settings, consts, core::errors}; #[cfg(not(feature = "olap"))] pub type StoreType = storage_impl::database::store::Store; @@ -40,61 +34,25 @@ pub type Store = RouterStore<StoreType>; #[cfg(feature = "kv_store")] pub type Store = KVRouterStore<StoreType>; +/// # Panics +/// +/// Will panic if hex decode of master key fails +#[allow(clippy::expect_used)] pub async fn get_store( - config: &settings::Settings, + config: &Settings, shut_down_signal: oneshot::Sender<()>, test_transaction: bool, ) -> StorageResult<Store> { - #[cfg(feature = "aws_kms")] - let aws_kms_client = aws_kms::core::get_aws_kms_client(&config.kms).await; - - #[cfg(feature = "hashicorp-vault")] - let hc_client = - external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault) - .await - .change_context(StorageError::InitializationError)?; - - let master_config = config.master_database.clone(); - - #[cfg(feature = "hashicorp-vault")] - let master_config = master_config - .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) - .await - .change_context(StorageError::InitializationError) - .attach_printable("Failed to fetch data from hashicorp vault")?; - - #[cfg(feature = "aws_kms")] - let master_config = master_config - .decrypt_inner(aws_kms_client) - .await - .change_context(StorageError::InitializationError) - .attach_printable("Failed to decrypt master database config")?; + let master_config = config.master_database.clone().into_inner(); #[cfg(feature = "olap")] - let replica_config = config.replica_database.clone(); - - #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] - let replica_config = replica_config - .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) - .await - .change_context(StorageError::InitializationError) - .attach_printable("Failed to fetch data from hashicorp vault")?; + let replica_config = config.replica_database.clone().into_inner(); - #[cfg(all(feature = "olap", feature = "aws_kms"))] - let replica_config = replica_config - .decrypt_inner(aws_kms_client) - .await - .change_context(StorageError::InitializationError) - .attach_printable("Failed to decrypt replica database config")?; + #[allow(clippy::expect_used)] + let master_enc_key = hex::decode(config.secrets.get_inner().master_enc_key.clone().expose()) + .map(StrongSecret::new) + .expect("Failed to decode master key from hex"); - let master_enc_key = get_master_enc_key( - config, - #[cfg(feature = "aws_kms")] - aws_kms_client, - #[cfg(feature = "hashicorp-vault")] - hc_client, - ) - .await; #[cfg(not(feature = "olap"))] let conf = master_config.into(); #[cfg(feature = "olap")] @@ -126,34 +84,6 @@ pub async fn get_store( Ok(store) } -#[allow(clippy::expect_used)] -async fn get_master_enc_key( - conf: &crate::configs::settings::Settings, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, - #[cfg(feature = "hashicorp-vault")] - hc_client: &external_services::hashicorp_vault::core::HashiCorpVault, -) -> StrongSecret<Vec<u8>> { - let master_enc_key = conf.secrets.master_enc_key.clone(); - - #[cfg(feature = "hashicorp-vault")] - let master_enc_key = master_enc_key - .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) - .await - .expect("Failed to fetch master enc key"); - - #[cfg(feature = "aws_kms")] - let master_enc_key = masking::Secret::<_, masking::WithType>::new( - master_enc_key - .decrypt_inner(aws_kms_client) - .await - .expect("Failed to decrypt master enc key"), - ); - - let master_enc_key = hex::decode(master_enc_key.peek()).expect("Failed to decode from hex"); - - StrongSecret::new(master_enc_key) -} - #[inline] pub fn generate_aes256_key() -> errors::CustomResult<[u8; 32], common_utils::errors::CryptoError> { use ring::rand::SecureRandom; diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 1c4d1810c88..738f57e9d70 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -29,7 +29,7 @@ use tera::{Context, Tera}; use self::request::{HeaderExt, RequestBuilderExt}; use super::authentication::AuthenticateAndFetch; use crate::{ - configs::settings::{Connectors, Settings}, + configs::{settings::Connectors, Settings}, consts, core::{ api_locking, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 455dc97d03e..7cf1855b441 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -3,14 +3,8 @@ use api_models::{payment_methods::PaymentMethodListRequest, payments}; use async_trait::async_trait; use common_utils::date_time; use error_stack::{report, IntoReport, ResultExt}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::decrypt::VaultFetch; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; -#[cfg(feature = "hashicorp-vault")] -use masking::ExposeInterface; -use masking::{PeekInterface, StrongSecret}; +use masking::PeekInterface; use serde::Serialize; use self::blacklist::BlackList; @@ -20,13 +14,14 @@ use super::jwt; #[cfg(feature = "recon")] use super::recon::ReconToken; #[cfg(feature = "olap")] +use crate::configs::Settings; +#[cfg(feature = "olap")] use crate::consts; #[cfg(feature = "olap")] use crate::core::errors::UserResult; #[cfg(feature = "recon")] use crate::routes::AppState; use crate::{ - configs::settings, core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, @@ -108,7 +103,7 @@ pub struct UserAuthToken { #[cfg(feature = "olap")] impl UserAuthToken { - pub async fn new_token(user_id: String, settings: &settings::Settings) -> UserResult<String> { + pub async fn new_token(user_id: String, settings: &Settings) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); let token_payload = Self { user_id, exp }; @@ -131,7 +126,7 @@ impl AuthToken { user_id: String, merchant_id: String, role_id: String, - settings: &settings::Settings, + settings: &Settings, org_id: String, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); @@ -224,16 +219,7 @@ where let api_key = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); - api_keys::get_hash_key( - &config.api_keys, - #[cfg(feature = "aws_kms")] - aws_kms::core::get_aws_kms_client(&config.kms).await, - #[cfg(feature = "hashicorp-vault")] - external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - ) - .await? + config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); @@ -285,41 +271,6 @@ where } } -static ADMIN_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = - tokio::sync::OnceCell::const_new(); - -pub async fn get_admin_api_key( - secrets: &settings::Secrets, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, - #[cfg(feature = "hashicorp-vault")] - hc_client: &external_services::hashicorp_vault::core::HashiCorpVault, -) -> RouterResult<&'static StrongSecret<String>> { - ADMIN_API_KEY - .get_or_try_init(|| async { - #[cfg(not(feature = "aws_kms"))] - let admin_api_key = secrets.admin_api_key.clone(); - - #[cfg(feature = "aws_kms")] - let admin_api_key = secrets - .kms_encrypted_admin_api_key - .decrypt_inner(aws_kms_client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to AWS KMS decrypt admin API key")?; - - #[cfg(feature = "hashicorp-vault")] - let admin_api_key = masking::Secret::new(admin_api_key) - .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to KMS decrypt admin API key")? - .expose(); - - Ok(StrongSecret::new(admin_api_key)) - }) - .await -} - #[derive(Debug)] pub struct UserWithoutMerchantJWTAuth; @@ -367,17 +318,7 @@ where get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let conf = state.conf(); - let admin_api_key = get_admin_api_key( - &conf.secrets, - #[cfg(feature = "aws_kms")] - aws_kms::core::get_aws_kms_client(&conf.kms).await, - #[cfg(feature = "hashicorp-vault")] - external_services::hashicorp_vault::core::get_hashicorp_client(&conf.hc_vault) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting admin api key")?, - ) - .await?; + let admin_api_key = &conf.secrets.get_inner().admin_api_key; if request_admin_api_key != admin_api_key.peek() { Err(report!(errors::ApiErrorResponse::Unauthorized) @@ -912,43 +853,12 @@ pub fn is_jwt_auth(headers: &HeaderMap) -> bool { headers.get(crate::headers::AUTHORIZATION).is_some() } -static JWT_SECRET: tokio::sync::OnceCell<StrongSecret<String>> = tokio::sync::OnceCell::const_new(); - -pub async fn get_jwt_secret( - secrets: &settings::Secrets, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, -) -> RouterResult<&'static StrongSecret<String>> { - JWT_SECRET - .get_or_try_init(|| async { - #[cfg(feature = "aws_kms")] - let jwt_secret = secrets - .kms_encrypted_jwt_secret - .decrypt_inner(aws_kms_client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to AWS KMS decrypt JWT secret")?; - - #[cfg(not(feature = "aws_kms"))] - let jwt_secret = secrets.jwt_secret.clone(); - - Ok(StrongSecret::new(jwt_secret)) - }) - .await -} - pub async fn decode_jwt<T>(token: &str, state: &impl AppStateInfo) -> RouterResult<T> where T: serde::de::DeserializeOwned, { let conf = state.conf(); - let secret = get_jwt_secret( - &conf.secrets, - #[cfg(feature = "aws_kms")] - aws_kms::core::get_aws_kms_client(&conf.kms).await, - ) - .await? - .peek() - .as_bytes(); + let secret = conf.secrets.get_inner().jwt_secret.peek().as_bytes(); let key = DecodingKey::from_secret(secret); decode::<T>(token, &key, &Validation::new(Algorithm::HS256)) @@ -1008,33 +918,6 @@ where default_auth } -#[cfg(feature = "recon")] -static RECON_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = - tokio::sync::OnceCell::const_new(); - -#[cfg(feature = "recon")] -pub async fn get_recon_admin_api_key( - secrets: &settings::Secrets, - #[cfg(feature = "aws_kms")] kms_client: &aws_kms::core::AwsKmsClient, -) -> RouterResult<&'static StrongSecret<String>> { - RECON_API_KEY - .get_or_try_init(|| async { - #[cfg(feature = "aws_kms")] - let recon_admin_api_key = secrets - .kms_encrypted_recon_admin_api_key - .decrypt_inner(kms_client) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to KMS decrypt recon admin API key")?; - - #[cfg(not(feature = "aws_kms"))] - let recon_admin_api_key = secrets.recon_admin_api_key.clone(); - - Ok(StrongSecret::new(recon_admin_api_key)) - }) - .await -} - #[cfg(feature = "recon")] pub struct ReconAdmin; @@ -1053,14 +936,9 @@ where get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let conf = state.conf(); - let admin_api_key = get_recon_admin_api_key( - &conf.secrets, - #[cfg(feature = "aws_kms")] - aws_kms::core::get_aws_kms_client(&conf.kms).await, - ) - .await?; + let admin_api_key = conf.secrets.get_inner().recon_admin_api_key.peek(); - if request_admin_api_key != admin_api_key.peek() { + if request_admin_api_key != admin_api_key { Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Recon Admin Authentication Failure"))?; } diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 46cfad08783..fa1eecbaab8 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -147,7 +147,7 @@ impl EmailToken { pub async fn new_token( email: domain::UserEmail, merchant_id: Option<String>, - settings: &configs::settings::Settings, + settings: &configs::Settings, ) -> CustomResult<String, UserErrors> { let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(expiration_duration)?.as_secs(); @@ -178,7 +178,7 @@ pub fn get_link_with_token( pub struct VerifyEmail { pub recipient_email: domain::UserEmail, - pub settings: std::sync::Arc<configs::settings::Settings>, + pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, } @@ -208,7 +208,7 @@ impl EmailData for VerifyEmail { pub struct ResetPassword { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, - pub settings: std::sync::Arc<configs::settings::Settings>, + pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, } @@ -238,7 +238,7 @@ impl EmailData for ResetPassword { pub struct MagicLink { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, - pub settings: std::sync::Arc<configs::settings::Settings>, + pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, } @@ -268,7 +268,7 @@ impl EmailData for MagicLink { pub struct InviteUser { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, - pub settings: std::sync::Arc<configs::settings::Settings>, + pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, pub merchant_id: String, } @@ -302,7 +302,7 @@ impl EmailData for InviteUser { pub struct InviteRegisteredUser { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, - pub settings: std::sync::Arc<configs::settings::Settings>, + pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, pub merchant_id: String, } @@ -339,7 +339,7 @@ impl EmailData for InviteRegisteredUser { pub struct ReconActivation { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, - pub settings: std::sync::Arc<configs::settings::Settings>, + pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, } @@ -365,7 +365,7 @@ pub struct BizEmailProd { pub legal_business_name: String, pub business_location: String, pub business_website: String, - pub settings: std::sync::Arc<configs::settings::Settings>, + pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, } @@ -413,7 +413,7 @@ pub struct ProFeatureRequest { pub feature_name: String, pub merchant_id: String, pub user_name: domain::UserName, - pub settings: std::sync::Arc<configs::settings::Settings>, + pub settings: std::sync::Arc<configs::Settings>, pub subject: String, } diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rs index 05de1b4e11e..6a78e2232a9 100644 --- a/crates/router/src/services/jwt.rs +++ b/crates/router/src/services/jwt.rs @@ -3,8 +3,7 @@ use error_stack::{IntoReport, ResultExt}; use jsonwebtoken::{encode, EncodingKey, Header}; use masking::PeekInterface; -use super::authentication; -use crate::{configs::settings::Settings, core::errors::UserErrors}; +use crate::{configs::Settings, core::errors::UserErrors}; pub fn generate_exp( exp_duration: std::time::Duration, @@ -24,14 +23,7 @@ pub async fn generate_jwt<T>( where T: serde::ser::Serialize, { - let jwt_secret = authentication::get_jwt_secret( - &settings.secrets, - #[cfg(feature = "aws_kms")] - external_services::aws_kms::core::get_aws_kms_client(&settings.kms).await, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to obtain JWT secret")?; + let jwt_secret = &settings.secrets.get_inner().jwt_secret; encode( &Header::default(), claims_data, diff --git a/crates/router/src/services/recon.rs b/crates/router/src/services/recon.rs index d5a2151a487..cc10fb7c7f5 100644 --- a/crates/router/src/services/recon.rs +++ b/crates/router/src/services/recon.rs @@ -3,9 +3,9 @@ use masking::Secret; use super::jwt; use crate::{ + configs::Settings, consts, core::{self, errors::RouterResult}, - routes::app::settings::Settings, }; #[derive(serde::Serialize, serde::Deserialize)] diff --git a/crates/router/src/utils/connector_onboarding/paypal.rs b/crates/router/src/utils/connector_onboarding/paypal.rs index 6d7f2692be7..ff9b5ab59e7 100644 --- a/crates/router/src/utils/connector_onboarding/paypal.rs +++ b/crates/router/src/utils/connector_onboarding/paypal.rs @@ -20,7 +20,8 @@ pub async fn generate_access_token(state: AppState) -> RouterResult<types::Acces &state.conf.connectors, connector.to_string().as_str(), )?; - let connector_auth = super::get_connector_auth(connector, &state.conf.connector_onboarding)?; + let connector_auth = + super::get_connector_auth(connector, state.conf.connector_onboarding.get_inner())?; connector::Paypal::get_access_token( &state, diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 30ac4815efb..3ba395c95a3 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -4,10 +4,6 @@ use api_models::enums; use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt}; use currency_conversion::types::{CurrencyFactors, ExchangeRates}; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::{self, decrypt::VaultFetch}; use masking::PeekInterface; use once_cell::sync::Lazy; use redis_interface::DelReply; @@ -128,9 +124,6 @@ async fn waited_fetch_and_update_caches( state: &AppState, local_fetch_retry_delay: u64, local_fetch_retry_count: u64, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { for _n in 1..local_fetch_retry_count { sleep(Duration::from_millis(local_fetch_retry_delay)).await; @@ -148,15 +141,7 @@ async fn waited_fetch_and_update_caches( } } //acquire lock one last time and try to fetch and update local & redis - successive_fetch_and_save_forex( - state, - None, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await + successive_fetch_and_save_forex(state, None).await } impl TryFrom<DefaultExchangeRates> for ExchangeRates { @@ -192,23 +177,11 @@ pub async fn get_forex_rates( call_delay: i64, local_fetch_retry_delay: u64, local_fetch_retry_count: u64, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { if let Some(local_rates) = retrieve_forex_from_local().await { if local_rates.is_expired(call_delay) { // expired local data - handler_local_expired( - state, - call_delay, - local_rates, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await + handler_local_expired(state, call_delay, local_rates).await } else { // Valid data present in local Ok(local_rates) @@ -220,10 +193,6 @@ pub async fn get_forex_rates( call_delay, local_fetch_retry_delay, local_fetch_retry_count, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, ) .await } @@ -234,46 +203,16 @@ async fn handler_local_no_data( call_delay: i64, _local_fetch_retry_delay: u64, _local_fetch_retry_count: u64, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { match retrieve_forex_from_redis(state).await { - Ok(Some(data)) => { - fallback_forex_redis_check( - state, - data, - call_delay, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await - } + Ok(Some(data)) => fallback_forex_redis_check(state, data, call_delay).await, Ok(None) => { // No data in local as well as redis - Ok(successive_fetch_and_save_forex( - state, - None, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await?) + Ok(successive_fetch_and_save_forex(state, None).await?) } Err(err) => { logger::error!(?err); - Ok(successive_fetch_and_save_forex( - state, - None, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await?) + Ok(successive_fetch_and_save_forex(state, None).await?) } } } @@ -281,36 +220,19 @@ async fn handler_local_no_data( async fn successive_fetch_and_save_forex( state: &AppState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { match acquire_redis_lock(state).await { Ok(lock_acquired) => { if !lock_acquired { return stale_redis_data.ok_or(ForexCacheError::CouldNotAcquireLock.into()); } - let api_rates = fetch_forex_rates( - state, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await; + let api_rates = fetch_forex_rates(state).await; match api_rates { Ok(rates) => successive_save_data_to_redis_local(state, rates).await, Err(err) => { // API not able to fetch data call secondary service logger::error!(?err); - let secondary_api_rates = fallback_fetch_forex_rates( - state, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await; + let secondary_api_rates = fallback_fetch_forex_rates(state).await; match secondary_api_rates { Ok(rates) => Ok(successive_save_data_to_redis_local(state, rates).await?), Err(err) => stale_redis_data.ok_or({ @@ -351,9 +273,6 @@ async fn fallback_forex_redis_check( state: &AppState, redis_data: FxExchangeRatesCacheEntry, call_delay: i64, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { match is_redis_expired(Some(redis_data.clone()).as_ref(), call_delay).await { Some(redis_forex) => { @@ -364,15 +283,7 @@ async fn fallback_forex_redis_check( } None => { // redis expired - successive_fetch_and_save_forex( - state, - Some(redis_data), - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await + successive_fetch_and_save_forex(state, Some(redis_data)).await } } } @@ -381,9 +292,6 @@ async fn handler_local_expired( state: &AppState, call_delay: i64, local_rates: FxExchangeRatesCacheEntry, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { match retrieve_forex_from_redis(state).await { Ok(redis_data) => { @@ -397,71 +305,22 @@ async fn handler_local_expired( } None => { // Redis is expired going for API request - successive_fetch_and_save_forex( - state, - Some(local_rates), - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await + successive_fetch_and_save_forex(state, Some(local_rates)).await } } } Err(e) => { // data not present in redis waited fetch logger::error!(?e); - successive_fetch_and_save_forex( - state, - Some(local_rates), - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, - ) - .await + successive_fetch_and_save_forex(state, Some(local_rates)).await } } } async fn fetch_forex_rates( state: &AppState, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexCacheError>> { - let forex_api_key = async { - #[cfg(feature = "hashicorp-vault")] - let client = hashicorp_vault::core::get_hashicorp_client(hc_config) - .await - .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - - #[cfg(not(feature = "hashicorp-vault"))] - let output = state.conf.forex_api.api_key.clone(); - #[cfg(feature = "hashicorp-vault")] - let output = state - .conf - .forex_api - .api_key - .clone() - .fetch_inner::<hashicorp_vault::core::Kv2>(client) - .await - .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - - Ok::<_, error_stack::Report<ForexCacheError>>(output) - } - .await?; - #[cfg(feature = "aws_kms")] - let forex_api_key = aws_kms::core::get_aws_kms_client(aws_kms_config) - .await - .decrypt(forex_api_key.peek()) - .await - .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - - #[cfg(not(feature = "aws_kms"))] - let forex_api_key = forex_api_key.peek(); + let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); let forex_url: String = format!("{}{}{}", FOREX_BASE_URL, forex_api_key, FOREX_BASE_CURRENCY); let forex_request = services::RequestBuilder::new() @@ -516,40 +375,8 @@ async fn fetch_forex_rates( pub async fn fallback_fetch_forex_rates( state: &AppState, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - let fallback_api_key = async { - #[cfg(feature = "hashicorp-vault")] - let client = hashicorp_vault::core::get_hashicorp_client(hc_config) - .await - .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - - #[cfg(not(feature = "hashicorp-vault"))] - let output = state.conf.forex_api.fallback_api_key.clone(); - #[cfg(feature = "hashicorp-vault")] - let output = state - .conf - .forex_api - .fallback_api_key - .clone() - .fetch_inner::<hashicorp_vault::core::Kv2>(client) - .await - .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - - Ok::<_, error_stack::Report<ForexCacheError>>(output) - } - .await?; - #[cfg(feature = "aws_kms")] - let fallback_forex_api_key = aws_kms::core::get_aws_kms_client(aws_kms_config) - .await - .decrypt(fallback_api_key.peek()) - .await - .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - - #[cfg(not(feature = "aws_kms"))] - let fallback_forex_api_key = fallback_api_key.peek(); + let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek(); let fallback_forex_url: String = format!("{}{}", FALLBACK_FOREX_BASE_URL, fallback_forex_api_key,); @@ -627,6 +454,7 @@ async fn release_redis_lock( } async fn acquire_redis_lock(app_state: &AppState) -> CustomResult<bool, ForexCacheError> { + let forex_api = app_state.conf.forex_api.get_inner(); app_state .store .get_redis_conn() @@ -635,9 +463,8 @@ async fn acquire_redis_lock(app_state: &AppState) -> CustomResult<bool, ForexCac REDIX_FOREX_CACHE_KEY, "", Some( - (app_state.conf.forex_api.local_fetch_retry_count - * app_state.conf.forex_api.local_fetch_retry_delay - + app_state.conf.forex_api.api_timeout) + (forex_api.local_fetch_retry_count * forex_api.local_fetch_retry_delay + + forex_api.api_timeout) .try_into() .into_report() .change_context(ForexCacheError::ConversionError)?, @@ -691,19 +518,13 @@ pub async fn convert_currency( amount: i64, to_currency: String, from_currency: String, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> { + let forex_api = state.conf.forex_api.get_inner(); let rates = get_forex_rates( &state, - state.conf.forex_api.call_delay, - state.conf.forex_api.local_fetch_retry_delay, - state.conf.forex_api.local_fetch_retry_count, - #[cfg(feature = "aws_kms")] - aws_kms_config, - #[cfg(feature = "hashicorp-vault")] - hc_config, + forex_api.call_delay, + forex_api.local_fetch_retry_delay, + forex_api.local_fetch_retry_count, ) .await .change_context(ForexCacheError::ApiError)?;
2024-02-15T19:07:44Z
## 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 incorporates the `hyperswitch_interface` crate into the router crate. Secondly, all secrets(configs) decryption now happens during application startup, eliminating runtime decryption. Lastly, the addition of an encryption_client in the AppState enables easy runtime encryption and decryption processes. ### 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 refactors the way decryption of secrets work in router. So all flows should work fine wherever secrets are being used. Flows that has secrets decryption involved and requires testing - * `merchant account` creation * `api key` creation * Hit `/health/ready` - Everything should be fine * `Add card` `Retrieve card` `Delete card` * `Currency conversion` flows * `Apple pay flow` - payment request with the decrypted apple pay token * Verify flow for applepay merchant verification * Payment method auth flow (Plaid) * connector onboarding flow ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
75c633fc7c37341177597041ccbcdfc3cf9e236f
juspay/hyperswitch
juspay__hyperswitch-3293
Bug: feat: List merchant id and merchant name
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index d666dfc3bfa..07909a35782 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -1,4 +1,4 @@ -use common_utils::pii; +use common_utils::{crypto::OptionalEncryptableName, pii}; use masking::Secret; use crate::user_role::UserStatus; @@ -133,3 +133,9 @@ pub type VerifyEmailResponse = DashboardEntryResponse; pub struct SendVerifyEmailRequest { pub email: pii::Email, } + +#[derive(Debug, serde::Serialize)] +pub struct UserMerchantAccount { + pub merchant_id: String, + pub merchant_name: OptionalEncryptableName, +} diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 6fb76bd75b3..532f8208ecf 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -640,9 +640,23 @@ pub async fn create_merchant_account( pub async fn list_merchant_ids_for_user( state: AppState, user: auth::UserFromToken, -) -> UserResponse<Vec<String>> { +) -> UserResponse<Vec<user_api::UserMerchantAccount>> { + let merchant_ids = utils::user_role::get_merchant_ids_for_user(&state, &user.user_id).await?; + + let merchant_accounts = state + .store + .list_multiple_merchant_accounts(merchant_ids) + .await + .change_context(UserErrors::InternalServerError)?; + Ok(ApplicationResponse::Json( - utils::user_role::get_merchant_ids_for_user(state, &user.user_id).await?, + merchant_accounts + .into_iter() + .map(|acc| user_api::UserMerchantAccount { + merchant_id: acc.merchant_id, + merchant_name: acc.merchant_name, + }) + .collect(), )) } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 4449338402f..c474a82981b 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -18,7 +18,7 @@ pub fn is_internal_role(role_id: &str) -> bool { || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER } -pub async fn get_merchant_ids_for_user(state: AppState, user_id: &str) -> UserResult<Vec<String>> { +pub async fn get_merchant_ids_for_user(state: &AppState, user_id: &str) -> UserResult<Vec<String>> { Ok(state .store .list_user_roles_by_user_id(user_id)
2024-01-09T07:39:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added Merchant name is list merchant api. <!-- 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 Dashboard needs to show merchant name is available. <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? ``` curl --location --request GET '<URL>/user/switch/list' \ --header 'Authorization: Bearer <JWT>' ``` Above api should return list of merchant accounts the user (whos jwt is being used) has access to. ``` [ { "merchant_id": "merchant_1704706726", "merchant_name": null }, { "merchant_id": "merchant_1704706837", "merchant_name": "some merchant name" } ] ``` <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ecf51b5e3a30f055634edfafcd36f64cef535a53
juspay/hyperswitch
juspay__hyperswitch-3292
Bug: Throw an error when outgoing webhook events env var not found
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 2b29a61b4a4..2bcfcfe974f 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -126,6 +126,15 @@ impl KafkaSettings { )) })?; + common_utils::fp_utils::when( + self.outgoing_webhook_logs_topic.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Outgoing Webhook Logs topic must not be empty".into(), + )) + }, + )?; + Ok(()) } }
2024-01-09T07:44:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Throw an error when outgoing webhook events env var not found ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ecf51b5e3a30f055634edfafcd36f64cef535a53
juspay/hyperswitch
juspay__hyperswitch-3309
Bug: [FEATURE] Add support for card extended bin in payment attempt ### Feature Description Card extended bin is initial 8 digit of card number. we need this field to be sent in payment attempt so that merchant can block payments based on this field too ### Possible Implementation Add a new field `card_extended_bin` in `AdditionalCardInfo` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 4ef0c540b51..7cc9296815b 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1129,6 +1129,7 @@ pub struct AdditionalCardInfo { pub bank_code: Option<String>, pub last4: Option<String>, pub card_isin: Option<String>, + pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, @@ -1665,6 +1666,7 @@ pub struct CardResponse { pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, + pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, @@ -1707,7 +1709,7 @@ pub enum VoucherData { #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { #[serde(rename = "card")] - Card(CardResponse), + Card(Box<CardResponse>), BankTransfer, Wallet, PayLater, @@ -2037,7 +2039,7 @@ pub struct PaymentsResponse { #[schema(example = 100)] pub amount: i64, - /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount, + /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount, /// If no surcharge_details, net_amount = amount #[schema(example = 110)] pub net_amount: i64, @@ -2528,6 +2530,7 @@ impl From<AdditionalCardInfo> for CardResponse { card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, + card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, @@ -2538,7 +2541,7 @@ impl From<AdditionalCardInfo> for CardResponse { impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { - AdditionalPaymentData::Card(card) => Self::Card(CardResponse::from(*card)), + AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater {} => Self::PayLater, AdditionalPaymentData::Wallet {} => Self::Wallet, AdditionalPaymentData::BankRedirect { .. } => Self::BankRedirect, diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index ca47c73c7c2..900f006eb4d 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -35,6 +35,9 @@ impl CardNumber { .rev() .collect::<String>() } + pub fn get_card_extended_bin(self) -> String { + self.0.peek().chars().take(8).collect::<String>() + } } impl FromStr for CardNumber { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d864cacc52f..17cc608d82d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3287,6 +3287,7 @@ pub async fn get_additional_payment_data( match pm_data { api_models::payments::PaymentMethodData::Card(card_data) => { let card_isin = Some(card_data.card_number.clone().get_card_isin()); + let card_extended_bin = Some(card_data.card_number.clone().get_card_extended_bin()); let last4 = Some(card_data.card_number.clone().get_last4()); if card_data.card_issuer.is_some() && card_data.card_network.is_some() @@ -3306,6 +3307,7 @@ pub async fn get_additional_payment_data( card_holder_name: card_data.card_holder_name.clone(), last4: last4.clone(), card_isin: card_isin.clone(), + card_extended_bin: card_extended_bin.clone(), }, )) } else { @@ -3329,6 +3331,7 @@ pub async fn get_additional_payment_data( card_issuing_country: card_info.card_issuing_country, last4: last4.clone(), card_isin: card_isin.clone(), + card_extended_bin: card_extended_bin.clone(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), @@ -3344,6 +3347,7 @@ pub async fn get_additional_payment_data( card_issuing_country: None, last4, card_isin, + card_extended_bin, card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(),
2024-01-10T11:22:12Z
## 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 --> Card extended bin is the initial 8 digits of card number. we need this field to be sent in payment attempt so that merchant can block payments based on this field too. This PR adds a new field `card_extended_bin` in `AdditionalCardInfo` struct which is mapped to `payment_method_data` in `payment_attempt` table. Also this field is added in payments retrieve response too. ### 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. Do a payment with card. You should be getting the `card_extended_bin` field in response ![image](https://github.com/juspay/hyperswitch/assets/70657455/ff2a0da3-ef7b-4415-9c15-e49bcd3f43f4) 2. Do a payment retrieve call using the `payment_id` from above call. You should get `card_extended_bin` field in response ![image](https://github.com/juspay/hyperswitch/assets/70657455/f8947f6b-bfbb-4a26-a4a6-8bf29c0d9a12) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fe3cf54781302c733c1682ded2c1735544407a5f
juspay/hyperswitch
juspay__hyperswitch-3274
Bug: Implement HashiCorp Vault support in the core application
diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 9bf4916eec3..f5fc4854086 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -38,3 +38,12 @@ pub mod metrics { #[cfg(feature = "kms")] histogram_metric!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for KMS encryption time (in sec) } + +// Mutually Exclusive - Feature Flags +// +// This are some feature flags that shouldn't be used together + +#[cfg(all(feature = "kms", feature = "hashicorp-vault"))] +compile_error!( + "feature \"kms\" and feature \"hashicorp-vault\" cannot be enabled at the same time" +); diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 72e3de0bf77..31282f7d734 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1446,9 +1446,9 @@ impl<F> resource_id: types::ResponseId::NoResponseId, redirection_data, mandate_reference: None, - connector_metadata: Some( - serde_json::json!({"three_ds_data":three_ds_data}), - ), + connector_metadata: Some(serde_json::json!({ + "three_ds_data": three_ds_data + })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 8beb81d9236..0abe1fff42c 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -2015,9 +2015,9 @@ impl<F> resource_id: types::ResponseId::NoResponseId, redirection_data, mandate_reference: None, - connector_metadata: Some( - serde_json::json!({"three_ds_data":three_ds_data}), - ), + connector_metadata: Some(serde_json::json!({ + "three_ds_data": three_ds_data + })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None,
2024-01-24T10:17:59Z
…d together ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add compiler error when `kms` and `hashicorp-vault` feature flag are enabled together. <!-- 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? <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3f343d36bff7ce8f73602a2391d205367d5581c7
juspay/hyperswitch
juspay__hyperswitch-3282
Bug: [BUG] [BOA/CYBERSOURCE] merchant_defined_information giving authentication error ### Bug Description Some payments fail when `merchant_defined_information` is passed for each payment with data coming from merchant in payment requests metadata. ### Expected Behavior All payments should succeed when `merchant_defined_information` is passed for each payment with data coming from merchant in payment requests metadata. ### Actual Behavior Some payments fail when `merchant_defined_information` is passed for each payment with data coming from merchant in payment requests metadata. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug Due to hashmap being used to populate key,value pairs in merchantDefinedInformation the order in which the (key,value) pairs gets inserted into merchantDefinedInformation is not fixed. Due to which for some payments there is a mismatch between the body used in generation of signature(in payments headers) and the body passed in the actual request. This mismatch causes the connector to throw authentication error for some payments. ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index def93ec5f83..aa47efbe714 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1,5 +1,3 @@ -use std::collections::HashMap; - use api_models::payments; use base64::Engine; use common_utils::pii; @@ -323,8 +321,9 @@ impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { fn foreign_from(metadata: Value) -> Self { - let hashmap: HashMap<String, Value> = - serde_json::from_str(&metadata.to_string()).unwrap_or(HashMap::new()); + let hashmap: std::collections::BTreeMap<String, Value> = + serde_json::from_str(&metadata.to_string()) + .unwrap_or(std::collections::BTreeMap::new()); let mut vector: Self = Self::new(); let mut iter = 1; for (key, value) in hashmap { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index cf769f1a2fd..e6034f7af7f 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1,5 +1,3 @@ -use std::collections::HashMap; - use api_models::payments; use base64::Engine; use common_utils::pii; @@ -543,8 +541,9 @@ fn build_bill_to( impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { fn foreign_from(metadata: Value) -> Self { - let hashmap: HashMap<String, Value> = - serde_json::from_str(&metadata.to_string()).unwrap_or(HashMap::new()); + let hashmap: std::collections::BTreeMap<String, Value> = + serde_json::from_str(&metadata.to_string()) + .unwrap_or(std::collections::BTreeMap::new()); let mut vector: Self = Self::new(); let mut iter = 1; for (key, value) in hashmap {
2024-01-08T17:01:35Z
## 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 --> Some payments fail when merchant_defined_information is passed for the payment with data coming from merchant in payment requests metadata. This was happening because hashmaps were being used to populate key,value pairs in merchantDefinedInformation due to which the order in which the (key,value) pairs gets inserted into merchantDefinedInformation was not fixed. Due to this for some payments there was a mismatch between the body used in generation of signature(for payments headers) and the body which was being passed in the actual request. This mismatch caused the connector to throw authentication error for those payments. ### 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/3282 ## 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 can be done by creating a card/gpay/applepay payment and by passing the following metadata in PAYMENTS-CREATE: `"metadata": { "count_tickets": 1, "transaction_number": "5590043" }` You should then be able to see the metadata on BOA dashboard for that payment: ![292885857-2693f174-0552-45a9-af42-6606e874231f](https://github.com/juspay/hyperswitch/assets/41580413/442f415a-b788-485a-88ad-9bf71dc934ba) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5484cf42426d37667266fb952b800a6dab5e305e
juspay/hyperswitch
juspay__hyperswitch-3296
Bug: [FEATURE]: [Cybersource] Add 3DS flow for cards ### Feature Description Add 3DS flow for cards ### Possible Implementation Add 3DS flow for cards ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 94f71fa3f70..e20f9c1b65d 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -351,6 +351,7 @@ stripe = { payment_method = "bank_transfer" } nuvei = { payment_method = "card" } shift4 = { payment_method = "card" } bluesnap = { payment_method = "card" } +cybersource = {payment_method = "card"} nmi = {payment_method = "card"} [dummy_connector] diff --git a/config/development.toml b/config/development.toml index 272b3641713..5732d5f0d1d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -428,6 +428,7 @@ stripe = {payment_method = "bank_transfer"} nuvei = {payment_method = "card"} shift4 = {payment_method = "card"} bluesnap = {payment_method = "card"} +cybersource = {payment_method = "card"} nmi = {payment_method = "card"} [connector_customer] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index e55353f8903..c6934a64671 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -241,6 +241,7 @@ stripe = {payment_method = "bank_transfer"} nuvei = {payment_method = "card"} shift4 = {payment_method = "card"} bluesnap = {payment_method = "card"} +cybersource = {payment_method = "card"} nmi = {payment_method = "card"} [dummy_connector] diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 6c4ea4c61fe..69159c10c8a 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -12,6 +12,7 @@ use time::OffsetDateTime; use transformers as cybersource; use url::Url; +use super::utils::{PaymentsAuthorizeRequestData, RouterData}; use crate::{ configs::settings, connector::{utils as connector_utils, utils::RefundsRequestData}, @@ -286,6 +287,8 @@ impl api::PaymentIncrementalAuthorization for Cybersource {} impl api::MandateSetup for Cybersource {} impl api::ConnectorAccessToken for Cybersource {} impl api::PaymentToken for Cybersource {} +impl api::PaymentsPreProcessing for Cybersource {} +impl api::PaymentsCompleteAuthorize for Cybersource {} impl api::ConnectorMandateRevoke for Cybersource {} impl @@ -472,6 +475,113 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme { } +impl + ConnectorIntegration< + api::PreProcessing, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + > for Cybersource +{ + fn get_headers( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let redirect_response = req.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => Ok(format!( + "{}risk/v1/authentications", + self.base_url(connectors) + )), + Some(_) | None => Ok(format!( + "{}risk/v1/authentication-results", + self.base_url(connectors) + )), + } + } + fn get_request_body( + &self, + req: &types::PaymentsPreProcessingRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = cybersource::CybersourceRouterData::try_from(( + &self.get_currency_unit(), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + req.request + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })?, + req, + ))?; + let connector_req = + cybersource::CybersourcePreProcessingRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPreProcessingType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPreProcessingType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsPreProcessingRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: cybersource::CybersourcePreProcessingResponse = res + .response + .parse_struct("Cybersource AuthEnrollmentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Cybersource { @@ -672,13 +782,20 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}pts/v2/payments/", - api::ConnectorCommon::base_url(self, connectors) - )) + if req.is_three_ds() && req.request.is_card() { + Ok(format!( + "{}risk/v1/authentication-setups", + api::ConnectorCommon::base_url(self, connectors) + )) + } else { + Ok(format!( + "{}pts/v2/payments/", + api::ConnectorCommon::base_url(self, connectors) + )) + } } fn get_request_body( @@ -692,9 +809,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.amount, req, ))?; - let connector_req = - cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + if req.is_three_ds() && req.request.is_card() { + let connector_req = + cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } else { + let connector_req = + cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } } fn build_request( @@ -722,6 +845,106 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + if data.is_three_ds() && data.request.is_card() { + let response: cybersource::CybersourceAuthSetupResponse = res + .response + .parse_struct("Cybersource AuthSetupResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } else { + let response: cybersource::CybersourcePaymentsResponse = res + .response + .parse_struct("Cybersource PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Cybersource +{ + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}pts/v2/payments/", + api::ConnectorCommon::base_url(self, connectors) + )) + } + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = cybersource::CybersourceRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = + cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: cybersource::CybersourcePaymentsResponse = res .response .parse_struct("Cybersource PaymentResponse") diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 8ae2ce29e5b..e83b23603e9 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1,6 +1,7 @@ use api_models::payments; use base64::Engine; -use common_utils::pii; +use common_utils::{ext_traits::ValueExt, pii}; +use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -8,10 +9,12 @@ use serde_json::Value; use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData, + PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RouterData, }, consts, core::errors, + services, types::{ self, api::{self, enums as api_enums}, @@ -200,7 +203,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { action_list, action_token_types, authorization_options, - commerce_indicator: CybersourceCommerceIndicator::Internet, + commerce_indicator: String::from("internet"), payment_solution: solution.map(String::from), }; Ok(Self { @@ -220,6 +223,8 @@ pub struct CybersourcePaymentsRequest { order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] + consumer_authentication_information: Option<CybersourceConsumerAuthInformation>, + #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } @@ -229,12 +234,22 @@ pub struct ProcessingInformation { action_list: Option<Vec<CybersourceActionsList>>, action_token_types: Option<Vec<CybersourceActionsTokenType>>, authorization_options: Option<CybersourceAuthorizationOptions>, - commerce_indicator: CybersourceCommerceIndicator, + commerce_indicator: String, capture: Option<bool>, capture_options: Option<CaptureOptions>, payment_solution: Option<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformation { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + directory_server_transaction_id: Option<String>, + specification_version: Option<String>, +} #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantDefinedInformation { @@ -282,12 +297,6 @@ pub enum CybersourcePaymentInitiatorTypes { Customer, } -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub enum CybersourceCommerceIndicator { - Internet, -} - #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CaptureOptions { @@ -450,6 +459,16 @@ impl From<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> } } +impl From<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for ClientReferenceInformation +{ + fn from(item: &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>) -> Self { + Self { + code: Some(item.router_data.connector_request_reference_id.clone()), + } + } +} + impl From<( &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, @@ -489,7 +508,56 @@ impl action_token_types, authorization_options, capture_options: None, - commerce_indicator: CybersourceCommerceIndicator::Internet, + commerce_indicator: String::from("internet"), + } + } +} + +impl + From<( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &CybersourceConsumerAuthValidateResponse, + )> for ProcessingInformation +{ + fn from( + (item, solution, three_ds_data): ( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &CybersourceConsumerAuthValidateResponse, + ), + ) -> Self { + let (action_list, action_token_types, authorization_options) = + if item.router_data.request.setup_future_usage.is_some() { + ( + Some(vec![CybersourceActionsList::TokenCreate]), + Some(vec![CybersourceActionsTokenType::PaymentInstrument]), + Some(CybersourceAuthorizationOptions { + initiator: CybersourcePaymentInitiator { + initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), + credential_stored_on_file: Some(true), + stored_credential_used: None, + }, + merchant_intitiated_transaction: None, + }), + ) + } else { + (None, None, None) + }; + Self { + capture: Some(matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + )), + payment_solution: solution.map(String::from), + action_list, + action_token_types, + authorization_options, + capture_options: None, + commerce_indicator: three_ds_data + .indicator + .to_owned() + .unwrap_or(String::from("internet")), } } } @@ -516,6 +584,28 @@ impl } } +impl + From<( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + )> for OrderInformationWithBill +{ + fn from( + (item, bill_to): ( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + ), + ) -> Self { + Self { + amount_details: Amount { + total_amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + }, + bill_to: Some(bill_to), + } + } +} + // for cybersource each item in Billing is mandatory fn build_bill_to( address_details: &payments::Address, @@ -602,6 +692,84 @@ impl payment_information, order_information, client_reference_information, + consumer_authentication_information: None, + merchant_defined_information, + }) + } +} + +impl + TryFrom<( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + )> for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + + let three_ds_info: CybersourceThreeDSMetadata = item + .router_data + .request + .connector_meta + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "connector_meta", + })? + .parse_value("CybersourceThreeDSMetadata") + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "Merchant connector account metadata", + })?; + + let processing_information = + ProcessingInformation::from((item, None, &three_ds_info.three_ds_data)); + + let consumer_authentication_information = Some(CybersourceConsumerAuthInformation { + ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator, + cavv: three_ds_info.three_ds_data.cavv, + ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data, + xid: three_ds_info.three_ds_data.xid, + directory_server_transaction_id: three_ds_info + .three_ds_data + .directory_server_transaction_id, + specification_version: three_ds_info.three_ds_data.specification_version, + }); + + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information, merchant_defined_information, }) } @@ -647,6 +815,7 @@ impl payment_information, order_information, client_reference_information, + consumer_authentication_information: None, merchant_defined_information, }) } @@ -689,6 +858,7 @@ impl payment_information, order_information, client_reference_information, + consumer_authentication_information: None, merchant_defined_information, }) } @@ -747,6 +917,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -810,6 +981,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } payments::PaymentMethodData::CardRedirect(_) @@ -832,6 +1004,64 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> } } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceAuthSetupRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, +} + +impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> + for CybersourceAuthSetupRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + Ok(Self { + payment_information, + client_reference_information, + }) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ) + .into()) + } + } + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsCaptureRequest { @@ -870,7 +1100,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>> action_token_types: None, authorization_options: None, capture: None, - commerce_indicator: CybersourceCommerceIndicator::Internet, + commerce_indicator: String::from("internet"), payment_solution: None, }, order_information: OrderInformationWithBill { @@ -909,7 +1139,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout reason: "5".to_owned(), }), }), - commerce_indicator: CybersourceCommerceIndicator::Internet, + commerce_indicator: String::from("internet"), capture: None, capture_options: None, payment_solution: None, @@ -1118,6 +1348,29 @@ pub struct CybersourceErrorInformationResponse { error_information: CybersourceErrorInformation, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationResponse { + access_token: String, + device_data_collection_url: String, + reference_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthSetupInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum CybersourceAuthSetupResponse { + ClientAuthSetupInfo(ClientAuthSetupInfoResponse), + ErrorInformation(CybersourceErrorInformationResponse), +} + #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsIncrementalAuthorizationResponse { @@ -1326,6 +1579,492 @@ impl<F> } } +impl<F> + TryFrom< + types::ResponseRouterData< + F, + CybersourceAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + CybersourceAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: Some(services::RedirectForm::CybersourceAuthSetup { + access_token: info_response + .consumer_authentication_information + .access_token, + ddc_url: info_response + .consumer_authentication_information + .device_data_collection_url, + reference_id: info_response + .consumer_authentication_information + .reference_id, + }), + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + }), + ..item.data + }), + CybersourceAuthSetupResponse::ErrorInformation(error_response) => { + let error_reason = error_response + .error_information + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason; + Ok(Self { + response: Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }), + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationRequest { + return_url: String, + reference_id: String, +} +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceAuthEnrollmentRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationRequest, + order_information: OrderInformationWithBill, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub struct CybersourceRedirectionAuthResponse { + pub transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationValidateRequest { + authentication_transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceAuthValidateRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationValidateRequest, + order_information: OrderInformation, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum CybersourcePreProcessingRequest { + AuthEnrollment(CybersourceAuthEnrollmentRequest), + AuthValidate(CybersourceAuthValidateRequest), +} + +impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> + for CybersourcePreProcessingRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&types::PaymentsPreProcessingRouterData>, + ) -> Result<Self, Self::Error> { + let client_reference_information = ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }; + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "payment_method_data", + }, + )?; + let payment_information = match payment_method_data { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + Ok(PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + })) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + )) + } + }?; + + let redirect_response = item.router_data.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + + let amount_details = Amount { + total_amount: item.amount.clone(), + currency: item.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + }, + )?, + }; + + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => { + let reference_id = param + .clone() + .peek() + .split_once('=') + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.params.reference_id", + })? + .1 + .to_string(); + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill { + amount_details, + bill_to: Some(bill_to), + }; + Ok(Self::AuthEnrollment(CybersourceAuthEnrollmentRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + CybersourceConsumerAuthInformationRequest { + return_url: item.router_data.request.get_complete_authorize_url()?, + reference_id, + }, + order_information, + })) + } + Some(_) | None => { + let redirect_payload: CybersourceRedirectionAuthResponse = redirect_response + .payload + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.payload", + })? + .peek() + .clone() + .parse_value("CybersourceRedirectionAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let order_information = OrderInformation { amount_details }; + Ok(Self::AuthValidate(CybersourceAuthValidateRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + CybersourceConsumerAuthInformationValidateRequest { + authentication_transaction_id: redirect_payload.transaction_id, + }, + order_information, + })) + } + } + } +} + +impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_data", + }, + )?; + match payment_method_data { + payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ) + .into()) + } + } + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CybersourceAuthEnrollmentStatus { + PendingAuthentication, + AuthenticationSuccessful, + AuthenticationFailed, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthValidateResponse { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + specification_version: Option<String>, + directory_server_transaction_id: Option<String>, + indicator: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct CybersourceThreeDSMetadata { + three_ds_data: CybersourceConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationEnrollmentResponse { + access_token: Option<String>, + step_up_url: Option<String>, + //Added to segregate the three_ds_data in a separate struct + #[serde(flatten)] + validate_response: CybersourceConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthCheckInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationEnrollmentResponse, + status: CybersourceAuthEnrollmentStatus, + error_information: Option<CybersourceErrorInformation>, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum CybersourcePreProcessingResponse { + ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), + ErrorInformation(CybersourceErrorInformationResponse), +} + +impl From<CybersourceAuthEnrollmentStatus> for enums::AttemptStatus { + fn from(item: CybersourceAuthEnrollmentStatus) -> Self { + match item { + CybersourceAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, + CybersourceAuthEnrollmentStatus::AuthenticationSuccessful => { + Self::AuthenticationSuccessful + } + CybersourceAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + CybersourcePreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + CybersourcePreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourcePreProcessingResponse::ClientAuthCheckInfo(info_response) => { + let status = enums::AttemptStatus::from(info_response.status); + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + let response = Err(types::ErrorResponse::from(( + &info_response.error_information, + &risk_info, + item.http_code, + info_response.id.clone(), + ))); + + Ok(Self { + status, + response, + ..item.data + }) + } else { + let connector_response_reference_id = Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ); + + let redirection_data = match ( + info_response + .consumer_authentication_information + .access_token, + info_response + .consumer_authentication_information + .step_up_url, + ) { + (Some(access_token), Some(step_up_url)) => { + Some(services::RedirectForm::CybersourceConsumerAuth { + access_token, + step_up_url, + }) + } + _ => None, + }; + let three_ds_data = serde_json::to_value( + info_response + .consumer_authentication_information + .validate_response, + ) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data, + mandate_reference: None, + connector_metadata: Some( + serde_json::json!({"three_ds_data":three_ds_data}), + ), + network_txn_id: None, + connector_response_reference_id, + incremental_authorization_allowed: None, + }), + ..item.data + }) + } + } + CybersourcePreProcessingResponse::ErrorInformation(ref error_response) => { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + Ok(Self { + response, + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + CybersourcePaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + CybersourcePaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourcePaymentsResponse::ClientReferenceInformation(info_response) => { + let status = enums::AttemptStatus::foreign_from(( + info_response.status.clone(), + item.data.request.is_auto_capture()?, + )); + let response = get_payment_response((&info_response, status, item.http_code)); + Ok(Self { + status, + response, + ..item.data + }) + } + CybersourcePaymentsResponse::ErrorInformation(ref error_response) => Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))), + } + } +} + impl<F> TryFrom< types::ResponseRouterData< @@ -1463,25 +2202,29 @@ impl<F, T> ..item.data }) } - CybersourceSetupMandatesResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id.clone()), - }) - }, - status: enums::AttemptStatus::Failure, - ..item.data - }), + CybersourceSetupMandatesResponse::ErrorInformation(ref error_response) => { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + Ok(Self { + response, + status: enums::AttemptStatus::Failure, + ..item.data + }) + } } } } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 55173f9b339..1040f020839 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -273,6 +273,7 @@ pub trait PaymentsPreProcessingData { fn get_webhook_url(&self) -> Result<String, Error>; fn get_return_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; + fn get_complete_authorize_url(&self) -> Result<String, Error>; } impl PaymentsPreProcessingData for types::PaymentsPreProcessingData { @@ -317,6 +318,11 @@ impl PaymentsPreProcessingData for types::PaymentsPreProcessingData { .clone() .ok_or_else(missing_field_err("browser_info")) } + fn get_complete_authorize_url(&self) -> Result<String, Error> { + self.complete_authorize_url + .clone() + .ok_or_else(missing_field_err("complete_authorize_url")) + } } pub trait PaymentsCaptureRequestData { @@ -592,6 +598,7 @@ pub trait PaymentsCompleteAuthorizeRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; + fn get_complete_authorize_url(&self) -> Result<String, Error>; } impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { @@ -616,6 +623,11 @@ impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { .into(), ) } + fn get_complete_authorize_url(&self) -> Result<String, Error> { + self.complete_authorize_url + .clone() + .ok_or_else(missing_field_err("complete_authorize_url")) + } } pub trait PaymentsSyncRequestData { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ff4934e1efc..21cdec92ccb 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1489,6 +1489,22 @@ where router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) + } else if connector.connector_name == router_types::Connector::Cybersource + && is_operation_complete_authorize(&operation) + && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs + { + router_data = router_data.preprocessing_steps(state, connector).await?; + + // Should continue the flow only if no redirection_data is returned else a response with redirection form shall be returned + let should_continue = matches!( + router_data.response, + Ok(router_types::PaymentsResponseData::TransactionResponse { + redirection_data: None, + .. + }) + ) && router_data.status + != common_enums::AttemptStatus::AuthenticationFailed; + (router_data, should_continue) } else { (router_data, should_continue_payment) } @@ -2106,6 +2122,10 @@ pub fn is_operation_confirm<Op: Debug>(operation: &Op) -> bool { matches!(format!("{operation:?}").as_str(), "PaymentConfirm") } +pub fn is_operation_complete_authorize<Op: Debug>(operation: &Op) -> bool { + matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") +} + #[cfg(feature = "olap")] pub async fn list_payments( state: AppState, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 27ddd3f6d81..6dd692f1525 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -154,7 +154,6 @@ default_imp_for_complete_authorize!( connector::Checkout, connector::Coinbase, connector::Cryptopay, - connector::Cybersource, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -873,7 +872,6 @@ default_imp_for_pre_processing_steps!( connector::Checkout, connector::Coinbase, connector::Cryptopay, - connector::Cybersource, connector::Dlocal, connector::Iatapay, connector::Fiserv, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index c934c7c2cd6..07af15a336d 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -412,6 +412,7 @@ impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentsPreProcessingData browser_info: data.browser_info, surcharge_details: data.surcharge_details, connector_transaction_id: None, + redirect_response: None, }) } } @@ -431,10 +432,11 @@ impl TryFrom<types::CompleteAuthorizeData> for types::PaymentsPreProcessingData order_details: None, router_return_url: None, webhook_url: None, - complete_authorize_url: None, + complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: None, connector_transaction_id: data.connector_transaction_id, + redirect_response: data.redirect_response, }) } } diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 2d52a145fea..68d0ee8d475 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -203,10 +203,19 @@ pub async fn complete_authorize_preprocessing_steps<F: Clone>( ], ); + let mut router_data_request = router_data.request.to_owned(); + + if let Ok(types::PaymentsResponseData::TransactionResponse { + connector_metadata, .. + }) = &resp.response + { + router_data_request.connector_meta = connector_metadata.to_owned(); + }; + let authorize_router_data = payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>( resp.clone(), - router_data.request.to_owned(), + router_data_request, resp.response, ); diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5a3a322fb14..dffcff23595 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1425,6 +1425,9 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; + let router_base_url = &additional_data.router_base_url; + let connector_name = &additional_data.connector_name; + let attempt = &payment_data.payment_attempt; let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info @@ -1446,7 +1449,11 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz .as_ref() .map(|surcharge_details| surcharge_details.final_amount) .unwrap_or(payment_data.amount.into()); - + let complete_authorize_url = Some(helpers::create_complete_authorize_url( + router_base_url, + attempt, + connector_name, + )); Ok(Self { setup_future_usage: payment_data.payment_intent.setup_future_usage, mandate_id: payment_data.mandate_id.clone(), @@ -1463,6 +1470,8 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz connector_transaction_id: payment_data.payment_attempt.connector_transaction_id, redirect_response, connector_meta: payment_data.payment_attempt.connector_metadata, + complete_authorize_url, + metadata: payment_data.payment_intent.metadata, }) } } @@ -1541,6 +1550,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce browser_info, surcharge_details: payment_data.surcharge_details, connector_transaction_id: payment_data.payment_attempt.connector_transaction_id, + redirect_response: None, }) } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index fdaaa87bf40..9eb06d675a0 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -789,6 +789,15 @@ pub enum RedirectForm { BlueSnap { payment_fields_token: String, // payment-field-token }, + CybersourceAuthSetup { + access_token: String, + ddc_url: String, + reference_id: String, + }, + CybersourceConsumerAuth { + access_token: String, + step_up_url: String, + }, Payme, Braintree { client_token: String, @@ -1426,6 +1435,105 @@ pub fn build_redirection_form( "))) }} } + RedirectForm::CybersourceAuthSetup { + access_token, + ddc_url, + reference_id, + } => { + maud::html! { + (maud::DOCTYPE) + html { + head { + meta name="viewport" content="width=device-width, initial-scale=1"; + } + body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { + + div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } + + (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) + + (PreEscaped(r#" + <script> + var anime = bodymovin.loadAnimation({ + container: document.getElementById('loader1'), + renderer: 'svg', + loop: true, + autoplay: true, + name: 'hyperswitch loader', + animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} + }) + </script> + "#)) + + + h3 style="text-align: center;" { "Please wait while we process your payment..." } + } + + (PreEscaped(r#"<iframe id="cardinal_collection_iframe" name="collectionIframe" height="10" width="10" style="display: none;"></iframe>"#)) + (PreEscaped(format!("<form id=\"cardinal_collection_form\" method=\"POST\" target=\"collectionIframe\" action=\"{ddc_url}\"> + <input id=\"cardinal_collection_form_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> + </form>"))) + (PreEscaped(r#"<script> + window.onload = function() { + var cardinalCollectionForm = document.querySelector('#cardinal_collection_form'); if(cardinalCollectionForm) cardinalCollectionForm.submit(); + } + </script>"#)) + (PreEscaped(format!("<script> + window.addEventListener(\"message\", function(event) {{ + if (event.origin === \"https://centinelapistag.cardinalcommerce.com\" || event.origin === \"https://centinelapi.cardinalcommerce.com\") {{ + window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\"); + }} + }}, false); + </script> + "))) + }} + } + RedirectForm::CybersourceConsumerAuth { + access_token, + step_up_url, + } => { + maud::html! { + (maud::DOCTYPE) + html { + head { + meta name="viewport" content="width=device-width, initial-scale=1"; + } + body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { + + div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } + + (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) + + (PreEscaped(r#" + <script> + var anime = bodymovin.loadAnimation({ + container: document.getElementById('loader1'), + renderer: 'svg', + loop: true, + autoplay: true, + name: 'hyperswitch loader', + animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} + }) + </script> + "#)) + + + h3 style="text-align: center;" { "Please wait while we process your payment..." } + } + + // This is the iframe recommended by cybersource but the redirection happens inside this iframe once otp + // is received and we lose control of the redirection on user client browser, so to avoid that we have removed this iframe and directly consumed it. + // (PreEscaped(r#"<iframe id="step_up_iframe" style="border: none; margin-left: auto; margin-right: auto; display: block" height="800px" width="400px" name="stepUpIframe"></iframe>"#)) + (PreEscaped(format!("<form id=\"step_up_form\" method=\"POST\" action=\"{step_up_url}\"> + <input id=\"step_up_form_jwt_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> + </form>"))) + (PreEscaped(r#"<script> + window.onload = function() { + var stepUpForm = document.querySelector('#step_up_form'); if(stepUpForm) stepUpForm.submit(); + } + </script>"#)) + }} + } RedirectForm::Payme => { maud::html! { (maud::DOCTYPE) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 7cd45a0192f..3521a82a5a8 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -490,6 +490,7 @@ pub struct PaymentsPreProcessingData { pub surcharge_details: Option<types::SurchargeDetails>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, + pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, } #[derive(Debug, Clone)] @@ -510,6 +511,8 @@ pub struct CompleteAuthorizeData { pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub connector_meta: Option<serde_json::Value>, + pub complete_authorize_url: Option<String>, + pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)]
2024-01-09T07:42:45Z
## 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 --> Implement 3DS flow for cards ``` Legend: UB: User Browser M: Merchant HS: Hyperswitch CS: Cybersource ``` ![Cybersource_3DS](https://github.com/juspay/hyperswitch/assets/55536657/eea4b266-970b-4f73-84c2-d19ca05a6ea2) ### 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). --> #3296 ## 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="1139" alt="Screenshot 2024-01-09 at 6 23 43 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/e6f5c024-2116-4946-ae67-802e1fc4a126"> <img width="1138" alt="Screenshot 2024-01-09 at 6 23 51 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/9db71df7-a0b4-4c85-b611-1eba611e1ab9"> <img width="934" alt="Screenshot 2024-01-09 at 6 23 56 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/1a37edcb-c0e9-4c94-890e-e1f55fbc1971"> <img width="1151" alt="Screenshot 2024-01-09 at 6 24 15 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/cf4dc934-097e-4080-96da-fd3689d57b06"> ### QA Testing - Test Non-3DS flows to confirm they are not affected - Test 3DS transactions - Test mandates + 3DS transaction (zero and non-zero) All the possible 3DS test cases and test cards are available here: https://developer.cybersource.com/content/dam/docs/cybs/en-us/payer-authentication/developer/all/rest/payer-auth.pdf ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
af43b07e4394458db478bc16e5fb8d3b0d636a31
juspay/hyperswitch
juspay__hyperswitch-3275
Bug: Implement HashiCorp Vault support in the Card Vault
diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rs index d7bd9721507..4aa132c4555 100644 --- a/crates/common_utils/src/custom_serde.rs +++ b/crates/common_utils/src/custom_serde.rs @@ -64,6 +64,9 @@ pub mod iso8601 { where S: Serializer, { + // FIXME(kos): There is no need to repeat the whole + // serialization/deserialization logic here. Just reuse + // it from the module above. date_time .map(|date_time| date_time.assume_utc().format(&Iso8601::<FORMAT_CONFIG>)) .transpose() diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 83770e6ca8c..12651910a79 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -211,6 +211,8 @@ impl<T> ValueExt<T> for serde_json::Value { where T: serde::de::DeserializeOwned, { + // FIXME(kos): The syntax `{self:?}` could be used here without any + // impact on semantics. let debug = format!( "Unable to parse {type_name} from serde_json::Value: {:?}", &self diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index 97b395b26d7..c219ff55398 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -56,12 +56,32 @@ where #[derive(Debug)] pub struct Email; +// FIXME(kos): Here should be not generic T, but newtype Email. impl<T> Strategy<T> for Email where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); + // FIXME(kos): We should assume constructed value object is already validated. + // Email validation is quite a heavy operation. Doing it on + // each formatting is quite a subtle performance penalty, + // while being... unnecessary? + // Another problem, that validation here is + // violation of the "Separation of concerns" design + // principle. Formatting is not a validation in any way. + // https://en.wikipedia.org/wiki/Separation_of_concerns + // Consider to provide a newtype for email strings. + // https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html + // This way you do the validation only once, when creating a + // value of the type, and then you may fearlessly reuse it + // as the type system protects you. + // https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate + // Thus, as the result, you will be able to remove any + // validation code from the formatting, as the compiler will + // guarantee that you would have valid values here. + // The same is true for other formatting strategies in this + // module too, as they're effectively validators too. let is_valid = validate_email(val_str); if is_valid.is_err() { @@ -80,11 +100,14 @@ where #[derive(Debug)] pub struct IpAddress; +// FIXME(kos): Here should be not generic T, but std::net::IpAddr. impl<T> Strategy<T> for IpAddress where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // TODO(kos): Consider to not use `String`s for IP addresses. + // There is a `std::net::IpAddr` for that. let val_str: &str = val.as_ref(); let segments: Vec<&str> = val_str.split('.').collect(); diff --git a/crates/masking/src/bytes.rs b/crates/masking/src/bytes.rs index e828f8a78e0..e1b415e36ee 100644 --- a/crates/masking/src/bytes.rs +++ b/crates/masking/src/bytes.rs @@ -77,6 +77,27 @@ impl<'de> Deserialize<'de> for SecretBytesMut { where V: de::SeqAccess<'de>, { + // FIXME(kos): Should be improved. Current logic: + // 1. If there is some `size_hint`, then we + // pre-allocate 4096 at max, and later, when + // filling the bytes will re-allocate the memory + // if `size_hint` > 4096. + // 2. If there is no `size_hint`, then we + // pre-allocate 0 bytes, and re-allocate normally + // when filling the bytes. + // So, what's no benefits of these moves? + // It seems more feasible to have: + // ```rust + // let len = seq.size_hint().unwrap_or(0); + // ``` + // This way: + // 1. If there is some `size_hint`, then we + // pre-allocate the exact size and fill it with + // the bytes without re-allocations. + // 2. If there is no `size_hint`, then we + // pre-allocate 4096 bytes, and re-allocate only + // if the real size is bigger than 4096 bytes. + // 4096 is cargo culted from upstream let len = core::cmp::min(seq.size_hint().unwrap_or(0), 4096); let mut bytes = BytesMut::with_capacity(len); diff --git a/crates/masking/src/strong_secret.rs b/crates/masking/src/strong_secret.rs index fd1335f6993..2f591e51305 100644 --- a/crates/masking/src/strong_secret.rs +++ b/crates/masking/src/strong_secret.rs @@ -9,6 +9,13 @@ use zeroize::{self, Zeroize as ZeroizableSecret}; use crate::{strategy::Strategy, PeekInterface}; +// FIXME(kos) : It would be convenient to implement Deref<Target=Thing> for Secret<Thing> +// This would allow getting rid of `peek()`. + +// FIXME(kos): Documentation should explain how it differs from the `Secret` +// type and why it's called "strong". Save the reader's time and +// free him from wondering and parsing the `impl`s of this type to +// understand the difference. /// /// Secret thing. /// @@ -62,6 +69,13 @@ where Self: PeekInterface<Secret>, Secret: ZeroizableSecret + StrongEq, { + // FIXME(kos): Usual comparison is not safe in cryptography as is lazy + // (fail-fast) and makes the code potentially vulnerable to + // timing attacks: + // https://www.chosenplaintext.ca/articles/beginners-guide-constant-time-cryptography.html + // Use crates like `subtle` for constant-time comparison of + // secret values: + // https://docs.rs/subtle fn eq(&self, other: &Self) -> bool { StrongEq::strong_eq(self.peek(), other.peek()) } diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 13eeee5043a..831d714321b 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -101,6 +101,8 @@ impl super::RedisConnectionPool { type_name: &str, ) -> CustomResult<T, errors::RedisError> where + // FIXME(kos): Just `Send` and `Sync` should be enough. No need in full path + // naming. T: serde::de::DeserializeOwned, { let value_bytes = self.get_key::<Vec<u8>>(key).await?; diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index 129c587298e..64b9044f16e 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -41,6 +41,9 @@ impl From<RedisEntryId> for fred::types::XID { } => XID::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), + // FIXME(kos): Why do these extra allocations here if we just need + // `&[u8]`? Either use `Cow` or `out.write_arg()` + // directly im match arms. RedisEntryId::AutoGeneratedID => XID::Auto, RedisEntryId::AfterLastID => XID::Max, RedisEntryId::UndeliveredEntryID => XID::NewInGroup, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 03d67edfa54..69047780e0b 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -91,7 +91,22 @@ pub struct Server { #[derive(Debug, Deserialize, Clone)] pub struct Database { + // TODO(kos): Consider using `Box<str>` here (and in similar places), as we + // don't need any `String` mutation capabilities for this field + // (after parsing it will only be read, but never mutated). pub username: String, + // FIXME(kos): Any kind of secrets, we control, should be wrapped into + // Secret, which will: + // 1. Protect any accidental secrets leaks to logs, traces or + // any other `Debug` prints. + // 2. Correctly zeroize the memory of secrets on `Drop` to avoid + // accidental secrets leaks when process is crashed and core + // dumped (by accessing the core dump file), process memory + // is swapped, etc. + // There is a similar, extended, but custom made functionality + // in the `masking` crate. So, the team is aware of the problem. + // But why then the `masking::Secret` is not used here and in + // similar places? pub password: String, pub host: String, pub port: u16, @@ -168,6 +183,12 @@ impl Settings { include_str!("defaults.toml"), FileFormat::Toml, )) + // FIXME(kos): `.required(true)` seems to be unnecessarily strict + // here. It's totally common scenario to run a process + // and provide it with environment variables only, + // without any config files. So, requiring a config file + // always to exist will be only a stumble factor for + // users. .add_source(File::from(config_path).required(true)) .add_source( Environment::with_prefix("ROUTER") @@ -180,6 +201,16 @@ impl Settings { .build()?; serde_path_to_error::deserialize(config).map_err(|error| { + // FIXME(kos): We can improve it. + // Usually, the logging system is initialized after the + // config parsing is done, as the config itself would + // likely have settings for logging setup. That's why + // doing logging here before the parsed config is + // returned is kinda strange thing. + // We can simply return the error. + // Let the caller decide what to do with this + // error. Hardcoded printing side effects here may be + // undesired by the caller. logger::error!(%error, "Unable to deserialize application configuration"); eprintln!("Unable to deserialize application configuration: {error}"); BachError::from(error.into_inner()) diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index a4944f1c4f4..3817b8dd8a9 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -156,6 +156,7 @@ pub struct AdyenCard { number: Option<Secret<String>>, expiry_month: Option<Secret<String>>, expiry_year: Option<Secret<String>>, + // FIXME(kos): CVC is a secret too! cvc: Option<String>, } @@ -306,6 +307,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest { expiry_year: ccard.map(|x| x.card_exp_year.peek().clone().into()), // TODO: CVV/CVC shouldn't be saved in our db // Will need to implement tokenization that allows us to make payments without cvv + // FIXME(kos): And this could be easily prevented if it was + // represented as a newtype for value object which doesn't implement + // `ToSql`. cvc: ccard.map(|x| x.card_cvc.peek().into()), }; diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 9e3815a767a..79b6a2858e2 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -41,6 +41,7 @@ impl TryFrom<&types::ConnectorAuthType> for MerchantAuthentication { #[derive(Serialize, PartialEq)] #[serde(rename_all = "camelCase")] struct CreditCardDetails { + // FIXME(kos): Why this is not a `Secret` as in other places? card_number: String, expiration_date: String, card_code: String, @@ -134,6 +135,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest { fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let payment_details = match item.request.payment_method_data { api::PaymentMethod::Card(ref ccard) => { + // FIXME(kos): The secrets here (and in similar places below) + // are cloned into the unprotected memory, and, + // thus, not properly zeroized on `Drop`. + // Furthermore, `.clone()` produces a redundant + // allocation here. It shouldn't be used, as + // the `format!()` macro bellow may easily accept a + // reference. let expiry_month = ccard.card_exp_month.peek().clone(); let expiry_year = ccard.card_exp_year.peek().clone(); @@ -194,6 +202,20 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelTransactionRequest { #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub enum AuthorizedotnetPaymentStatus { + // FIXME(kos): Instead of such renaming, it would be more properly to use + // `#[repr(u8)]` here: + // ```rust + // #[derive(Serialize_repr, Deserialize_repr)] + // #[repr(u8)] + // pub enum AuthorizedotnetPaymentStatus { + // Approved = 1, + // Declined = 2, + // Error = 3, + // #[default] + // HeldForReview = 4, + // } + // ``` + // https://serde.rs/enum-number.html #[serde(rename = "1")] Approved, #[serde(rename = "2")] @@ -287,6 +309,21 @@ impl<F, T> .transaction_response .errors .and_then(|errors| { + // FIXME(kos): Two redundant allocations here are introduced due + // to `.clone()` usage. + // We do own `errors` vector here, not borrow it, so + // we may directly consume its first element and its + // values without any cloning: + // ```rust + // errors + // .into_iter() + // .next() + // .map(|err| types::ErrorResponse { + // code: err.error_code, + // message: err.error_text, + // reason: None, + // }) + // ``` errors.first().map(|error| types::ErrorResponse { code: error.error_code.clone(), message: error.error_text.clone(), diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 1e0cbd6df5a..74ad303dd9d 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -40,6 +40,19 @@ impl api::ConnectorCommon for Checkout { &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + // FIXME(kos): Just every implementation of this `get_auth_header()` + // method in this codebase uses a statically predefined + // value for the first element of the returned tuple. So, + // why do redundant allocations with `.to_string()` then? + // Why not just return `&'static str` or, if we do really + // want to allow dynamic values, at least + // `Cow<'static, str>`? + // The same is valid for + // `ConnectorIntegration::get_headers()` (and similar ones) + // too. + // Or even use framework's header: + // https://docs.rs/http/0.2.8/http/header/struct.HeaderName.html + let auth: checkout::CheckoutAuthType = auth_type .try_into() .change_context(errors::ConnectorError::FailedToObtainAuthType)?; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index d14489ba692..02efe3a3600 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -17,7 +17,18 @@ use crate::{ #[inline] fn create_merchant_api_key() -> String { + // FIXME(kos): Why duplicate `&Uuid::new_v4().simple().to_string()` line + // three times? Better DRY it out into a separate value and + // reuse: + // ```rust + // let id = Uuid::new_v4().simple(); + // ``` match env::which() { + // FIXME(kos): Using `.to_string()` here just does a redundant + // allocation without giving any benefit. + // Just use `Uuid::new_v4().simple()` directly, which + // implements `Display` anyway, so can be written directly + // into the formatter without intermediate allocations. Env::Development => format!("dev_{}", &Uuid::new_v4().simple().to_string()), Env::Production => format!("prd_{}", &Uuid::new_v4().simple().to_string()), Env::Sandbox => format!("snd_{}", &Uuid::new_v4().simple().to_string()), @@ -59,6 +70,8 @@ pub async fn create_merchant_account( routing_algorithm: req.routing_algorithm.map(ForeignInto::foreign_into), custom_routing_rules: Some(custom_routing_rules), sub_merchants_enabled: req.sub_merchants_enabled, + // FIXME(kos) : possible race condition here. what if a concurrent user updates + // parent merchant between this operation and the following? parent_merchant_id: get_parent_merchant( db, &req.sub_merchants_enabled, @@ -133,6 +146,8 @@ pub async fn merchant_account_update( merchant_id: &String, req: api::CreateMerchantAccount, ) -> RouterResponse<api::MerchantAccountResponse> { + // FIXME(kos) : possible race condition here. what if a concurrent user updates + // merchant account between this read and the last write? let merchant_account = db .find_merchant_account_by_merchant_id(merchant_id) .await @@ -191,6 +206,8 @@ pub async fn merchant_account_update( sub_merchants_enabled: req .sub_merchants_enabled .or(merchant_account.sub_merchants_enabled), + // FIXME(kos) : possible race condition here. what if a concurrent user updates + // parent merchant between this operation and the following? parent_merchant_id: get_parent_merchant( db, &req.sub_merchants_enabled diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 88dbb652cb7..0cc1c365194 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -128,6 +128,18 @@ pub enum ApiErrorResponse { impl ::core::fmt::Display for ApiErrorResponse { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // FIXME(kos): `serde_json::to_string(self)` here makes a redundant + // allocation, which may be omitted by writing into the + // formatter directly via `serde_json::to_writer()`: + // ```rust + // write!(f, r#"{{"error":"#)?; + // serde_json::to_writer(f, self) + // .map(|_| fmt::Error::default())?; + // write!(f, "}") + // ``` + // FIXME(kos): `.unwrap_or_else()` logic here is just incorrect. + // Better map the error and return it as in the example + // above. write!( f, r#"{{"error":{}}}"#, @@ -140,6 +152,10 @@ impl actix_web::ResponseError for ApiErrorResponse { fn status_code(&self) -> reqwest::StatusCode { use reqwest::StatusCode; + // FIXME(kos): Use `Self::Unauthorized` syntax here (and in similar + // places), as more ergonomic. + // `#![warn(clippy::use_self)]` on crate level should help + // with this. match self { ApiErrorResponse::Unauthorized | ApiErrorResponse::BadCredentials diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 862c075346f..4707e9d8ebd 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -665,9 +665,18 @@ pub async fn delete_payment_method( error.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) })?; + // FIXME!(kos): What if the application process would be killed after + // successful execution of + // `delete_payment_method_by_merchant_id_payment_method_id()`, + // but before executing `delete_card()`? + // Would be the card ever deleted? + // Seems like the system has weak consistency guarantees. + // https://docs.diesel.rs/diesel/connection/trait.Connection.html#method.transaction if pm.payment_method == enums::PaymentMethodType::Card { let response = delete_card(state, &pm.merchant_id, &pm.payment_method_id).await?; if response.status == "success" { + // FIXME(kos): Why writing to STDOUT in blocking and unstructured + // manner? Use `log::info!()` instead. print!("Card From locker deleted Successfully") } else { print!("Error: Deleting Card From Locker") diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 73d4077917d..9f4c385f8a0 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -457,6 +457,10 @@ where pub payment_intent: storage::PaymentIntent, pub payment_attempt: storage::PaymentAttempt, pub connector_response: storage::ConnectorResponse, + // FIXME(kos) : It is incorrect to use i32 as payment amount. Use decimal instead. + // first, there are situations where 2**31 would overflow. + // second, payment shouldn't have negative amounts. + // third, decimal place may be not shared. pub amount: api::Amount, pub currency: enums::Currency, pub mandate_id: Option<String>, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index f61de78d2af..8444ac23a23 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -332,7 +332,10 @@ pub async fn refund_update_core( } // ********************************************** VALIDATIONS ********************************************** - +// FIXME(kos) : this function doesn't follow ACID principle, since the validation +// and the update is performed using multiple queries not in a single transaction. +// For example, two concurrent requests can pass validation on refund amount, +// and bypass maximum refund amount limitation. Thus, atomicity and consistency is broken. #[instrument(skip_all)] pub async fn validate_and_create_refund( state: &AppState, @@ -366,6 +369,8 @@ pub async fn validate_and_create_refund( .attach_printable("invalid merchant_id in request")), )?; + // FIXME(kos) : There's a race condition here. it's possible for two clients to check that + // refund doesn't exist and try to create one at the same time. let refund = match validator::validate_uniqueness_of_refund_id_against_merchant_id( db, &payment_intent.payment_id, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index de83d4e94ff..95ffd26c984 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -1,6 +1,20 @@ +// FIXME(kos): Here and in any other crate roots it's better to declare +// `#![forbid(unsafe_code)]` as we do in `batch_pii` crate. +// This will ease a life of readers and auditors a lot, and will +// require quite a reasoning for those who will intend to contribute +// any `unsafe` code. + +// TODO(kos): Consider always adding `#![forbid(non_ascii_idents)]` to crate +// roots, unless there is a real need in some exotic or math notation +// in the code. This prevents any fuckups with accidental unicode +// characters similarity. + // FIXME: I strongly advise to add this worning. // #![warn(missing_docs)] +// FIXME(kos): Codebase has many such problems. Use it. +// #![warn(clippy::use_self)] + // FIXME: I recommend to add these wornings too, although there is no harm if these wanrings will stay disabled. // #![warn(rust_2018_idioms)] // #![warn(missing_debug_implementations)] diff --git a/crates/router/src/scheduler/consumer.rs b/crates/router/src/scheduler/consumer.rs index 92cf5723569..abb954b4c01 100644 --- a/crates/router/src/scheduler/consumer.rs +++ b/crates/router/src/scheduler/consumer.rs @@ -85,6 +85,8 @@ pub async fn consumer_operations( settings: &settings::SchedulerSettings, ) -> CustomResult<(), errors::ProcessTrackerError> { let stream_name = settings.stream.clone(); + // FIXME(kos): Why `String` when `consumer_group_create()` accepts + // `&str`? let group_name = settings.consumer_group.clone(); let consumer_name = format!("consumer_{}", Uuid::new_v4()); diff --git a/crates/router/src/scheduler/producer.rs b/crates/router/src/scheduler/producer.rs index a190cf9104e..bcdef9da2e5 100644 --- a/crates/router/src/scheduler/producer.rs +++ b/crates/router/src/scheduler/producer.rs @@ -49,7 +49,16 @@ pub async fn start_producer( options.looper_interval.milliseconds, )); + // TODO(kos): The loop is not panic safe. It won't be automatically restored + // if a panic happens. So the external machinery should take care + // to restart the process if this happens. + // Either catch panic with catch_unwind or restart process externally. + // https://docs.rs/futures/0.3.25/futures/future/trait.FutureExt.html#method.catch_unwind loop { + // FIXME(kos) : If the scheduler is going to sleep for some time, + // then process events, the time between start of event processing + // will be off by the time taken to process events. + // Is it necessary to have precise interval between event processing? interval.tick().await; let is_ready = options.readiness.is_ready; diff --git a/crates/router/src/scheduler/types/batch.rs b/crates/router/src/scheduler/types/batch.rs index bd81d093a95..15db3de5004 100644 --- a/crates/router/src/scheduler/types/batch.rs +++ b/crates/router/src/scheduler/types/batch.rs @@ -49,6 +49,19 @@ impl ProcessTrackerBatch { pub fn from_redis_stream_entry( entry: HashMap<String, Option<String>>, ) -> CustomResult<Self, errors::ProcessTrackerError> { + // FIXME(kos) : the MissingRequiredField could include the missing field name. + // .change_context(errors::ProcessTrackerError::MissingRequiredField("id"))?; + // FIXME(kos) : the code is quite repetitive, is there a way to make it shorter, like with a macro? + // macro_rules! get_field { + // ($entry:expr, $field:expr) => { + // $entry + // .get($field) + // .get_required_value($field) + // .change_context(errors::ProcessTrackerError::MissingRequiredField($field))? + // } + // } + // let id = get_field!(entry, "id"); + let mut entry = entry; let id = entry .remove("id") diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index f69149b62b7..9721304ca7e 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -362,6 +362,10 @@ pub enum ApiAuthentication<'a> { Connector(ConnectorAuthentication<'a>), } +// FIXME(kos) : Is it correct to call this MerchantAuthentication, considering +// there's AdminApiKey as a variant? +// The name implies that authentication is only performed for Merchants, +// however, AdminApiKey implies it's an admin user. #[derive(Clone, Debug)] pub enum MerchantAuthentication<'a> { ApiKey, @@ -536,6 +540,10 @@ pub async fn authenticate_merchant<'a>( } MerchantAuthentication::AdminApiKey => { + // FIXME(kos) : It looks like admin credentials are hard-coded below. + // It is a securiry problem to store credentials in the code. + // e.g. if request.password != "hunter2" { return Err(...) } + let admin_api_key = get_api_key(request).change_context(errors::ApiErrorResponse::Unauthorized)?; if admin_api_key != "test_admin" { diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index 04cb0413c42..88c3956fd4b 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -10,6 +10,7 @@ use crate::{ logger, }; +// FIXME(kos) : Why not use reqwest::RequestBuilder + make an extension? pub(crate) type Headers = Vec<(String, String)>; #[derive( diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 58a029b1350..5eab93a9634 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -253,6 +253,7 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { // Different patterns of authentication. #[derive(Debug, Clone, serde::Deserialize)] #[serde(tag = "auth_type")] +// FIXME(kos): Shouldn't these keys be `Secret`? pub enum ConnectorAuthType { HeaderKey { api_key: String, diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index ef0b24a69ec..ac742d4ecab 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -34,6 +34,14 @@ pub mod error_parser { // Display is a requirement defined by the actix crate for implementing ResponseError trait impl Display for CustomJsonError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // FIXME(kos): This code contains redundant heap allocation `.to_string()` + // allocations, because we can write directly into the + // formatter: + // ```rust + // write!(f, "{}", serde_json::json!({ + // "error": &self.err + // })) + // ``` f.write_str( serde_json::to_string(&serde_json::json!({ "error": self.err.to_string() diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 8e6240d3487..872da0fdbec 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -158,6 +158,7 @@ pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { + // FIXME(kos) : `is_merchant_flow` seems to be too use-case specific, maybe `is_authenticated`? quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs index 8ef88d13c65..5a5a466a7f7 100644 --- a/crates/router_derive/src/macros.rs +++ b/crates/router_derive/src/macros.rs @@ -19,6 +19,14 @@ pub(crate) fn debug_as_display_inner(ast: &DeriveInput) -> syn::Result<TokenStre Ok(quote! { impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause { + // FIXME(kos): Redundant allocation on heap. + // This code produces the redundant `String` + // allocation as the result of `format!()` macro + // call. Omit it by writing into the formatter + // directly with `write!()` macro: + // ```rust + // ::core::write!(f, "{:?}", self) + // ``` fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { f.write_str(&format!("{:?}", self)) } diff --git a/crates/router_derive/src/macros/api_error.rs b/crates/router_derive/src/macros/api_error.rs index cdf14bbfdcc..61ed3661dfa 100644 --- a/crates/router_derive/src/macros/api_error.rs +++ b/crates/router_derive/src/macros/api_error.rs @@ -173,6 +173,8 @@ fn implement_serialize( let error_type_enum = type_properties.error_type_enum.as_ref().unwrap(); let response_definition = if msg_unused_fields.is_empty() { + // FIXME(kos): Redundant structure. + // It's possible to drop it and get better peformance and simpler code. quote! { #[derive(Clone, Debug, serde::Serialize)] struct ErrorResponse { diff --git a/crates/router_derive/src/macros/api_error/helpers.rs b/crates/router_derive/src/macros/api_error/helpers.rs index b2997090785..14f85c78b2c 100644 --- a/crates/router_derive/src/macros/api_error/helpers.rs +++ b/crates/router_derive/src/macros/api_error/helpers.rs @@ -222,6 +222,12 @@ pub(super) fn check_missing_attributes( /// Get all the fields not used in the error message. pub(super) fn get_unused_fields(fields: &Fields, message: &str) -> syn::Result<Vec<Field>> { let fields = match fields { + // FIXME(kos): Restructure it as: + // ```rust + // Fields::Unit | Fields::Unnamed(_) => vec![], + // ``` + // `#![warn(clippy::match_same_arms)]` on crate level should + // help with this. syn::Fields::Unit => Vec::new(), syn::Fields::Unnamed(_) => Vec::new(), syn::Fields::Named(fields) => fields.named.iter().cloned().collect(), diff --git a/crates/router_derive/src/macros/diesel.rs b/crates/router_derive/src/macros/diesel.rs index 932d45b7f4d..a7a4b4c9cc2 100644 --- a/crates/router_derive/src/macros/diesel.rs +++ b/crates/router_derive/src/macros/diesel.rs @@ -20,6 +20,11 @@ pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenSt #[diesel(postgres_type(name = #type_name))] pub struct #struct_name; + // FIXME(kos): Consider to mark any new code/items, generated by + // procedural macros, with the `#[automatically_derived]` + // attribute. This makes code style linters to omit the + // generated code and doesn't report redundant warnings. + // Example: https://github.com/cucumber-rs/cucumber/blob/v0.15.1/codegen/src/world.rs impl #impl_generics ::diesel::serialize::ToSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics #where_clause { diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index e234635aabc..89c9454e984 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -89,6 +89,10 @@ impl From<String> for Conversion { "update_tracker" => Self::UpdateTracker, "post_tracker" => Self::PostUpdateTracker, "all" => Self::All, + // FIXME(kos) : proc macro should not panic. When proc macro panics, + // it will be the only error message returned by the rust compiler. + // Instead, in case of errors, proc macro should emit compile_error!() + // to communicate error to the user. This will allow other errors to be displayed. _ => panic!("Invalid conversion identifier {}", s), } } @@ -157,6 +161,7 @@ impl Conversion { } } + // FIXME(kos) : why is it necessary to have a separate impl for this fn to_ref_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs index 114fad09335..b95533b4385 100644 --- a/crates/router_env/src/logger/config.rs +++ b/crates/router_env/src/logger/config.rs @@ -48,6 +48,25 @@ pub struct LogFile { // pub rotation: u16, } +// FIXME(kos): It could be done in a better way. As far as +// `serde` provides `#[serde(deserialize_with = ...)]` attribute: +// ```rust +// #[derive(Debug, Deserialize, Clone)] +// pub struct LogFile { +// // ... +// /// What gets into log files. +// `#[serde(deserialize_with = "deserialize_level")]` +// pub level: tracing::Level, +// // ... +// } +// fn deserialize_level<'de, D: Deserializer<'de>>( +// d: D, +// ) -> Result<tracing::Level, D::Error> { +// tracing::Level::from_str(&*<Cow<'_, str>>::deserialize(d)?) +// .map_err(D::Error::custom) +// } +// ``` +// See more: https://serde.rs/field-attrs.html#deserialize_with /// Describes the level of verbosity of a span or event. #[derive(Debug, Clone)] pub struct Level(tracing::Level); @@ -96,6 +115,9 @@ pub struct LogTelemetry { #[derive(Default, Debug, Deserialize, Clone, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum LogFormat { + // FIXME(kos): `Default` is quite a generic naming here, giving no idea about + // what the format is. Better name it either `Pretty`, or + // `Compact` (the terminology used by `slog` crate). /// Default pretty log format Default, /// JSON based structured logging diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs index 11d9abc66bc..1ceaf79d4c1 100644 --- a/crates/router_env/src/logger/formatter.rs +++ b/crates/router_env/src/logger/formatter.rs @@ -111,6 +111,9 @@ pub enum RecordType { impl fmt::Display for RecordType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let repr = match self { + // FIXME(kos): Use `Self::EnterSpan` syntax here. + // `#![warn(clippy::use_self)]` on crate level should + // help with this. RecordType::EnterSpan => "START", RecordType::ExitSpan => "END", RecordType::Event => "EVENT", @@ -204,6 +207,10 @@ where map_serializer.serialize_entry(ENV, &self.env)?; map_serializer.serialize_entry(VERSION, &self.version)?; map_serializer.serialize_entry(BUILD, &self.build)?; + // FIXME(kos): Use here, below, and in similar places, the + // `format_args!()` macro instead, to omit redundant + // allocations produced by the `format!()` macro (as it + // returns a new `String`). map_serializer.serialize_entry(LEVEL, &format!("{}", metadata.level()))?; map_serializer.serialize_entry(TARGET, metadata.target())?; map_serializer.serialize_entry(SERVICE, &self.service)?; diff --git a/crates/router_env/src/logger/macros.rs b/crates/router_env/src/logger/macros.rs index c3398e98c64..f0443db33df 100644 --- a/crates/router_env/src/logger/macros.rs +++ b/crates/router_env/src/logger/macros.rs @@ -1,3 +1,5 @@ +// FIXME(kos): We can remove the file now. + //! //! Macros. //! diff --git a/crates/storage_models/src/refund.rs b/crates/storage_models/src/refund.rs index adf189665a4..b4bf6f8ba6b 100644 --- a/crates/storage_models/src/refund.rs +++ b/crates/storage_models/src/refund.rs @@ -17,8 +17,12 @@ pub struct Refund { pub pg_refund_id: Option<String>, pub external_reference_id: Option<String>, pub refund_type: storage_enums::RefundType, + // FIXME(kos): It is incorrect to use i32 as payment amount. Use decimal instead. + // same as PaymentData::amount pub total_amount: i32, pub currency: storage_enums::Currency, + // FIXME(kos): It is incorrect to use i32 as payment amount. Use decimal instead. + // same as PaymentData::amount pub refund_amount: i32, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool,
2022-12-05T09:39:28Z
Thorough code review
6bf99048673c9a8f02dfe6f061226da03fc1aadb
juspay/hyperswitch
juspay__hyperswitch-3272
Bug: [FEATURE] [BOA/Cybersource] Store AVS Response in connector metadata ### Feature Description The AVS fields in payments response for authorize flow should be stored in connector metadata. ### Possible Implementation The AVS fields in payments response for authorize flow should be stored in connector metadata. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index 1e0856a9ccc..aeb3dafcfa2 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -205,7 +205,7 @@ impl ConnectorCommon for Bankofamerica { }; match response { transformers::BankOfAmericaErrorResponse::StandardError(response) => { - let (code, message) = match response.error_information { + let (code, connector_reason) = match response.error_information { Some(ref error_info) => (error_info.reason.clone(), error_info.message.clone()), None => ( response @@ -218,13 +218,13 @@ impl ConnectorCommon for Bankofamerica { .map_or(error_message.to_string(), |message| message), ), }; - let connector_reason = match response.details { + let message = match response.details { Some(details) => details .iter() .map(|det| format!("{} : {}", det.field, det.reason)) .collect::<Vec<_>>() .join(", "), - None => message.clone(), + None => connector_reason.clone(), }; Ok(ErrorResponse { diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index e024eb7a501..6abe1b634df 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -343,6 +343,30 @@ pub struct ClientReferenceInformation { code: Option<String>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientProcessorInformation { + avs: Option<Avs>, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientRiskInformation { + rules: Option<Vec<ClientRiskInformationRules>>, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ClientRiskInformationRules { + name: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Avs { + code: String, + code_raw: String, +} + impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -658,10 +682,12 @@ pub struct BankOfAmericaClientReferenceResponse { id: String, status: BankofamericaPaymentStatus, client_reference_information: ClientReferenceInformation, + processor_information: Option<ClientProcessorInformation>, + risk_information: Option<ClientRiskInformation>, error_information: Option<BankOfAmericaErrorInformation>, } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaErrorInformationResponse { id: String, @@ -674,6 +700,55 @@ pub struct BankOfAmericaErrorInformation { message: Option<String>, } +impl<F, T> + From<( + &BankOfAmericaErrorInformationResponse, + types::ResponseRouterData<F, BankOfAmericaPaymentsResponse, T, types::PaymentsResponseData>, + Option<enums::AttemptStatus>, + )> for types::RouterData<F, T, types::PaymentsResponseData> +{ + fn from( + (error_response, item, transaction_status): ( + &BankOfAmericaErrorInformationResponse, + types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + T, + types::PaymentsResponseData, + >, + Option<enums::AttemptStatus>, + ), + ) -> Self { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + match transaction_status { + Some(status) => Self { + response, + status, + ..item.data + }, + None => Self { + response, + ..item.data + }, + } + } +} + fn get_error_response_if_failure( (info_response, status, http_code): ( &BankOfAmericaClientReferenceResponse, @@ -684,6 +759,7 @@ fn get_error_response_if_failure( if utils::is_payment_failure(status) { Some(types::ErrorResponse::from(( &info_response.error_information, + &info_response.risk_information, http_code, info_response.id.clone(), ))) @@ -706,7 +782,10 @@ fn get_payment_response( resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: None, mandate_reference: None, - connector_metadata: None, + connector_metadata: info_response + .processor_information + .as_ref() + .map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})), network_txn_id: None, connector_response_reference_id: Some( info_response @@ -752,26 +831,13 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - status: enums::AttemptStatus::Failure, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))) + } } } } @@ -806,24 +872,9 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from((&error_response.clone(), item, None))) + } } } } @@ -858,24 +909,9 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from((&error_response.clone(), item, None))) + } } } } @@ -927,10 +963,12 @@ impl<F> app_response.application_information.status, item.data.request.is_auto_capture()?, )); + let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(types::ErrorResponse::from(( &app_response.error_information, + &risk_info, item.http_code, app_response.id.clone(), ))), @@ -1213,8 +1251,8 @@ pub struct BankOfAmericaAuthenticationErrorResponse { #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum BankOfAmericaErrorResponse { - StandardError(BankOfAmericaStandardErrorResponse), AuthenticationError(BankOfAmericaAuthenticationErrorResponse), + StandardError(BankOfAmericaStandardErrorResponse), } #[derive(Debug, Deserialize, Clone)] @@ -1235,29 +1273,53 @@ pub struct AuthenticationErrorInformation { pub rmsg: String, } -impl From<(&Option<BankOfAmericaErrorInformation>, u16, String)> for types::ErrorResponse { +impl + From<( + &Option<BankOfAmericaErrorInformation>, + &Option<ClientRiskInformation>, + u16, + String, + )> for types::ErrorResponse +{ fn from( - (error_data, status_code, transaction_id): ( + (error_data, risk_information, status_code, transaction_id): ( &Option<BankOfAmericaErrorInformation>, + &Option<ClientRiskInformation>, u16, String, ), ) -> Self { - let error_message = error_data + let avs_message = risk_information .clone() - .and_then(|error_details| error_details.message); + .map(|client_risk_information| { + client_risk_information.rules.map(|rules| { + rules + .iter() + .map(|risk_info| format!(" , {}", risk_info.name)) + .collect::<Vec<String>>() + .join("") + }) + }) + .unwrap_or(Some("".to_string())); let error_reason = error_data + .clone() + .map(|error_details| { + error_details.message.unwrap_or("".to_string()) + + &avs_message.unwrap_or("".to_string()) + }) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_data .clone() .and_then(|error_details| error_details.reason); Self { - code: error_reason + code: error_message .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason + message: error_message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_message.clone(), + reason: Some(error_reason.clone()), status_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(transaction_id.clone()), diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 33503102e4b..6c4ea4c61fe 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -124,7 +124,7 @@ impl ConnectorCommon for Cybersource { }; match response { transformers::CybersourceErrorResponse::StandardError(response) => { - let (code, message) = match response.error_information { + let (code, connector_reason) = match response.error_information { Some(ref error_info) => (error_info.reason.clone(), error_info.message.clone()), None => ( response @@ -137,13 +137,13 @@ impl ConnectorCommon for Cybersource { .map_or(error_message.to_string(), |message| message), ), }; - let connector_reason = match response.details { + let message = match response.details { Some(details) => details .iter() .map(|det| format!("{} : {}", det.field, det.reason)) .collect::<Vec<_>>() .join(", "), - None => message.clone(), + None => connector_reason.clone(), }; Ok(types::ErrorResponse { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index bc69fb78129..8ae2ce29e5b 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1105,6 +1105,8 @@ pub struct CybersourceClientReferenceResponse { id: String, status: CybersourcePaymentStatus, client_reference_information: ClientReferenceInformation, + processor_information: Option<ClientProcessorInformation>, + risk_information: Option<ClientRiskInformation>, token_information: Option<CybersourceTokenInformation>, error_information: Option<CybersourceErrorInformation>, } @@ -1136,6 +1138,30 @@ pub struct ClientReferenceInformation { code: Option<String>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientProcessorInformation { + avs: Option<Avs>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Avs { + code: String, + code_raw: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientRiskInformation { + rules: Option<Vec<ClientRiskInformationRules>>, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ClientRiskInformationRules { + name: String, +} + #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceTokenInformation { @@ -1152,10 +1178,11 @@ impl<F, T> From<( &CybersourceErrorInformationResponse, types::ResponseRouterData<F, CybersourcePaymentsResponse, T, types::PaymentsResponseData>, + Option<enums::AttemptStatus>, )> for types::RouterData<F, T, types::PaymentsResponseData> { fn from( - (error_response, item): ( + (error_response, item, transaction_status): ( &CybersourceErrorInformationResponse, types::ResponseRouterData< F, @@ -1163,25 +1190,35 @@ impl<F, T> T, types::PaymentsResponseData, >, + Option<enums::AttemptStatus>, ), ) -> Self { - Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message.clone(), - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id.clone()), - }) + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + match transaction_status { + Some(status) => Self { + response, + status, + ..item.data + }, + None => Self { + response, + ..item.data }, - ..item.data } } } @@ -1196,6 +1233,7 @@ fn get_error_response_if_failure( if utils::is_payment_failure(status) { Some(types::ErrorResponse::from(( &info_response.error_information, + &info_response.risk_information, http_code, info_response.id.clone(), ))) @@ -1229,7 +1267,10 @@ fn get_payment_response( resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: None, mandate_reference, - connector_metadata: None, + connector_metadata: info_response + .processor_information + .as_ref() + .map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})), network_txn_id: None, connector_response_reference_id: Some( info_response @@ -1276,25 +1317,11 @@ impl<F> ..item.data }) } - CybersourcePaymentsResponse::ErrorInformation(error_response) => { - let error_reason = &error_response.error_information.reason; - Ok(Self { - response: Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id.clone()), - }), - status: enums::AttemptStatus::Failure, - ..item.data - }) - } + CybersourcePaymentsResponse::ErrorInformation(ref error_response) => Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))), } } } @@ -1330,7 +1357,7 @@ impl<F> }) } CybersourcePaymentsResponse::ErrorInformation(ref error_response) => { - Ok(Self::from((&error_response.clone(), item))) + Ok(Self::from((&error_response.clone(), item, None))) } } } @@ -1367,7 +1394,7 @@ impl<F> }) } CybersourcePaymentsResponse::ErrorInformation(ref error_response) => { - Ok(Self::from((&error_response.clone(), item))) + Ok(Self::from((&error_response.clone(), item, None))) } } } @@ -1556,10 +1583,12 @@ impl<F> )); let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); + let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(types::ErrorResponse::from(( &app_response.error_information, + &risk_info, item.http_code, app_response.id.clone(), ))), @@ -1782,30 +1811,53 @@ pub struct AuthenticationErrorInformation { pub rmsg: String, } -impl From<(&Option<CybersourceErrorInformation>, u16, String)> for types::ErrorResponse { +impl + From<( + &Option<CybersourceErrorInformation>, + &Option<ClientRiskInformation>, + u16, + String, + )> for types::ErrorResponse +{ fn from( - (error_data, status_code, transaction_id): ( + (error_data, risk_information, status_code, transaction_id): ( &Option<CybersourceErrorInformation>, + &Option<ClientRiskInformation>, u16, String, ), ) -> Self { - let error_message = error_data + let avs_message = risk_information .clone() - .and_then(|error_details| error_details.message); - + .map(|client_risk_information| { + client_risk_information.rules.map(|rules| { + rules + .iter() + .map(|risk_info| format!(" , {}", risk_info.name)) + .collect::<Vec<String>>() + .join("") + }) + }) + .unwrap_or(Some("".to_string())); let error_reason = error_data + .clone() + .map(|error_details| { + error_details.message.unwrap_or("".to_string()) + + &avs_message.unwrap_or("".to_string()) + }) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_data .clone() .and_then(|error_details| error_details.reason); Self { - code: error_reason + code: error_message .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason + message: error_message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_message.clone(), + reason: Some(error_reason.clone()), status_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(transaction_id.clone()),
2024-01-08T09:39:35Z
## 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 --> This PR contains the following changes for BOA/Cybersource: 1. The AVS response being sent by BOA/Cybersource for authorize flow is being stored in `connector_metadata` 2. In case of payments failing due to AVS check the failure reason will also contain the details of the AVS Check 3. In case of general failures the response message is used to populate our error reason and response details is used to populate our error message. ### 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` 4. `crates/router/src/configs` 5. `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/3272 ## 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 successful payment and verify that avs_response is stored in connector_metadata in db for the payment <img width="1073" alt="image" src="https://github.com/juspay/hyperswitch/assets/41580413/ceed3f94-523c-424a-be4d-32657b193416"> Curl for creating payment: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "029" } }, "billing": { "address": { "line1": "cq", "city": "dshcvjhdw", "state": "whecvjkcdv", "zip": "46205", "country": "MW", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "12345", "country_code": "+93" } }, "metadata": { "count_tickets": 1, "transaction_number": "12321" }, "business_label": "food", "business_country": "US" }' ``` connector_response: ```json Ok(Ok(Response { headers: Some({"cache-control": "no-cache, no-store, must-revalidate", "pragma": "no-cache", "expires": "-1", "strict-transport-security": "max-age=31536000", "content-type": "application/hal+json", "content-length": "1621", "x-response-time": "1481ms", "x-opnet-transaction-trace": "HIDDEN", "connection": "keep-alive", "v-c-correlation-id": "HIDDEN"}), response: b"{\"_links\":{\"void\":{\"method\":\"POST\",\"href\":\"/pts/v2/payments/7049799548496957104951/voids\"},\"self\":{\"method\":\"GET\",\"href\":\"/pts/v2/payments/7049799548496957104951\"}},\"clientReferenceInformation\":{\"code\":\"pay_D0hUwTOaupjcu8P2qqcH_1\"},\"consumerAuthenticationInformation\":{\"token\":\"HIDDEN"},\"id\":\"7049799548496957104951\",\"orderInformation\":{\"amountDetails\":{\"totalAmount\":\"14.04\",\"authorizedAmount\":\"14.04\",\"currency\":\"USD\"}},\"paymentAccountInformation\":{\"card\":{\"type\":\"001\"}},\"paymentInformation\":{\"tokenizedCard\":{\"type\":\"001\"},\"scheme\":\"VISA DEBIT\",\"bin\":\"411111\",\"accountType\":\"Visa Classic\",\"issuer\":\"HIDDEN SP. Z O.O\",\"card\":{\"type\":\"001\"},\"binCountry\":\"PL\"},\"processorInformation\":{\"systemTraceAuditNumber\":\"HIDDEN\",\"approvalCode\":\"HIDDEN\",\"cardVerification\":{\"resultCodeRaw\":\"M\",\"resultCode\":\"M\"},\"merchantAdvice\":{\"code\":\"01\",\"codeRaw\":\"M001\"},\"responseDetails\":\"ABC\",\"networkTransactionId\":\"HIDDEN\",\"retrievalReferenceNumber\":\"HIDDEN\",\"consumerAuthenticationResponse\":{\"code\":\"2\",\"codeRaw\":\"2\"},\"transactionId\":\"HIDDEN\",\"responseCode\":\"00\",**\"avs\":{\"code\":\"Y\",\"codeRaw\":\"Y\"}},**\"reconciliationId\":\"HIDDEN\",\"riskInformation\":{\"localTime\":\"15:32:34\",\"score\":{\"result\":\"68\",\"factorCodes\":[\"B\"],\"modelUsed\":\"default_cemea\"},\"infoCodes\":{\"address\":[\"MM-BIN\",\"UNV-ADDR\"],\"identityChange\":[\"ID-X-HPOS\"]},\"profile\":{\"earlyDecision\":\"ACCEPT\",\"name\":\"Standard mid-market profile\",\"selectorRule\":\"Default Active Profile\"}},\"status\":\"AUTHORIZED\",\"submitTimeUtc\":\"2024-01-11T13:32:35Z\"}", status_code: 201 })) ``` 2. Testing can be done by creating a AVS mismatch error for a payment. You should see the following details in the error_message. (AVS Mismatch can be triggered by enabling Fraud Rules on BOA/Cybersource Dashboard) ```json { "payment_id": "pay_p6jsWMZ0Rdi2eZTasuTm", "merchant_id": "merchant_1704716850", "status": "failed", "amount": 1404, "net_amount": 1404, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_p6jsWMZ0Rdi2eZTasuTm_secret_7P0lx3N6COfGLvS4yBRl", "created": "2024-01-11T13:37:01.254Z", "currency": "USD", "customer_id": "CustomerX", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "dshcvjhdw", "country": "MW", "line1": "cq", "line2": null, "line3": null, "zip": "46205", "state": "whecvjkcdv", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "12345", "country_code": "+93" } }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "DECISION_PROFILE_REJECT", "error_message": "The order has been rejected by Decision Manager , Fraud Score - Reject", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": "cybersource_US_food_default", "business_country": "US", "business_label": "food", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1704980221, "expires": 1704983821, "secret": "epk_83a362750bd34f1f85c1a3303905bf4b" }, "manual_retry_allowed": true, "connector_transaction_id": "7049802214936686604953", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590043" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_aLMwDWebJFLj05EIBPCm", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_x7psrN0rGR7OOaljMXC3", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null } ``` ![Screenshot 2024-01-11 at 7 07 40 PM](https://github.com/juspay/hyperswitch/assets/41580413/f43168ea-21db-4032-abb4-968884b20447) 3. To create a general failure pass line1 as empty string. You should see the following error_message. ![Screenshot 2024-01-08 at 7 55 02 PM](https://github.com/juspay/hyperswitch/assets/41580413/71342cc7-3d55-4b1c-9ce1-b23dd3765f89) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9eaebe8db3d83105ef1e8fc784241e1fb795dd22
juspay/hyperswitch
juspay__hyperswitch-3270
Bug: Deep health check for Hyperswitch Card Vault Components to be verified in this check - [x] RDS (PostgreSQL) - Connection to Database - State of Migration (v2) - [x] Key Custodian State
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index 27611334fe0..e7c131a4a49 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -39,7 +39,9 @@ pub struct CustomerId { #[derive(Default, Debug, Deserialize, Serialize)] pub struct CustomerDeleteResponse { pub customer_id: String, - pub deleted: bool, + pub customer_deleted: bool, + pub address_deleted: bool, + pub payment_methods_deleted: bool, } pub fn generate_customer_id() -> String { diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index 590f7995925..2dec79707d4 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -111,9 +111,7 @@ pub async fn customer_delete( &state, &req, payload, - |state, merchant_account, req| { - customers::delete_customer(&*state.store, merchant_account, req) - }, + customers::delete_customer, api::MerchantAuthentication::ApiKey, ) .await diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index 8b1716d7e74..015bd516cb2 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -104,7 +104,7 @@ impl From<api::CustomerDeleteResponse> for CustomerDeleteResponse { fn from(cust: api::CustomerDeleteResponse) -> Self { Self { id: cust.customer_id, - deleted: cust.deleted, + deleted: cust.customer_deleted, } } } diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index f2f38ee997f..0ee8c8a3d2a 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -55,6 +55,12 @@ pub(crate) enum ErrorCode { #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] DuplicateRefundRequest, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")] + MandateActive, + + #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")] + CustomerRedacted, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")] RefundNotFound, @@ -340,6 +346,8 @@ impl From<ApiErrorResponse> for ErrorCode { ApiErrorResponse::RefundFailed { data } => ErrorCode::RefundFailed, // Nothing at stripe to map ApiErrorResponse::InternalServerError => ErrorCode::InternalServerError, // not a stripe code + ApiErrorResponse::MandateActive => ErrorCode::MandateActive, //not a stripe code + ApiErrorResponse::CustomerRedacted => ErrorCode::CustomerRedacted, //not a stripe code ApiErrorResponse::DuplicateRefundRequest => ErrorCode::DuplicateRefundRequest, ApiErrorResponse::RefundNotFound => ErrorCode::RefundNotFound, ApiErrorResponse::CustomerNotFound => ErrorCode::CustomerNotFound, @@ -433,9 +441,10 @@ impl actix_web::ResponseError for ErrorCode { | ErrorCode::ResourceIdNotFound | ErrorCode::PaymentIntentMandateInvalid { .. } | ErrorCode::PaymentIntentUnexpectedState { .. } => StatusCode::BAD_REQUEST, - ErrorCode::RefundFailed | ErrorCode::InternalServerError => { - StatusCode::INTERNAL_SERVER_ERROR - } + ErrorCode::RefundFailed + | ErrorCode::InternalServerError + | ErrorCode::MandateActive + | ErrorCode::CustomerRedacted => StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, } } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index e0981bca4ff..fdc7e375a8d 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -2,12 +2,16 @@ use error_stack::ResultExt; use router_env::{tracing, tracing::instrument}; use crate::{ - core::errors::{self, RouterResponse, StorageErrorExt}, + core::{ + errors::{self, RouterResponse, StorageErrorExt}, + payment_methods::cards, + }, db::StorageInterface, + routes::AppState, services, types::{ api::customers::{self, CustomerRequestExt}, - storage, + storage::{self, enums}, }, }; @@ -63,20 +67,99 @@ pub async fn retrieve_customer( Ok(services::BachResponse::Json(response.into())) } -#[instrument(skip(db))] +#[instrument(skip_all)] pub async fn delete_customer( - db: &dyn StorageInterface, + state: &AppState, merchant_account: storage::MerchantAccount, req: customers::CustomerId, ) -> RouterResponse<customers::CustomerDeleteResponse> { - let response = db - .delete_customer_by_customer_id_merchant_id(&req.customer_id, &merchant_account.merchant_id) + let db = &state.store; + + let cust = db + .find_customer_by_customer_id_merchant_id(&req.customer_id, &merchant_account.merchant_id) .await - .map(|response| customers::CustomerDeleteResponse { - customer_id: req.customer_id, - deleted: response, - }) - .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound))?; + .map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound))?; + if cust.name == Some("Redacted".to_string()) { + Err(errors::ApiErrorResponse::CustomerRedacted)? + } + + let customer_mandates = db + .find_mandate_by_merchant_id_customer_id(&merchant_account.merchant_id, &req.customer_id) + .await + .map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::MandateNotFound))?; + + for mandate in customer_mandates.into_iter() { + if mandate.mandate_status == enums::MandateStatus::Active { + Err(errors::ApiErrorResponse::MandateActive)? + } + } + + let customer_payment_methods = db + .find_payment_method_by_customer_id_merchant_id_list( + &req.customer_id, + &merchant_account.merchant_id, + ) + .await + .map_err(|err| { + err.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) + })?; + for pm in customer_payment_methods.into_iter() { + if pm.payment_method == enums::PaymentMethodType::Card { + cards::delete_card(state, &merchant_account.merchant_id, &pm.payment_method_id).await?; + } + db.delete_payment_method_by_merchant_id_payment_method_id( + &merchant_account.merchant_id, + &pm.payment_method_id, + ) + .await + .map_err(|error| { + error.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) + })?; + } + + let update_address = storage::AddressUpdate::Update { + city: Some("Redacted".to_string()), + country: Some("Redacted".to_string()), + line1: Some("Redacted".to_string().into()), + line2: Some("Redacted".to_string().into()), + line3: Some("Redacted".to_string().into()), + state: Some("Redacted".to_string().into()), + zip: Some("Redacted".to_string().into()), + first_name: Some("Redacted".to_string().into()), + last_name: Some("Redacted".to_string().into()), + phone_number: Some("Redacted".to_string().into()), + country_code: Some("Redacted".to_string()), + }; + db.update_address_by_merchant_id_customer_id( + &req.customer_id, + &merchant_account.merchant_id, + update_address, + ) + .await + .change_context(errors::ApiErrorResponse::AddressNotFound)?; + + let updated_customer = storage::CustomerUpdate::Update { + name: Some("Redacted".to_string()), + email: Some("Redacted".to_string().into()), + phone: Some("Redacted".to_string().into()), + description: Some("Redacted".to_string()), + phone_country_code: Some("Redacted".to_string()), + metadata: None, + }; + db.update_customer_by_customer_id_merchant_id( + req.customer_id.clone(), + merchant_account.merchant_id, + updated_customer, + ) + .await + .change_context(errors::ApiErrorResponse::CustomerNotFound)?; + + let response = customers::CustomerDeleteResponse { + customer_id: req.customer_id, + customer_deleted: true, + address_deleted: true, + payment_methods_deleted: true, + }; Ok(services::BachResponse::Json(response)) } diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 88dbb652cb7..12cc827e702 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -28,8 +28,6 @@ pub enum ApiErrorResponse { the Dashboard Settings section." )] BadCredentials, - #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Invalid Ephemeral Key for the customer")] - InvalidEphermeralKey, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "Unrecognized request URL.")] InvalidRequestUrl, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "The HTTP method is not applicable for this API.")] @@ -46,14 +44,20 @@ pub enum ApiErrorResponse { }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "{message}")] InvalidRequestData { message: String }, - #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Refund amount exceeds the payment amount.")] - RefundAmountExceedsPaymentAmount, /// Typically used when a field has invalid value, or deserialization of the value contained in /// a field fails. #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}.")] InvalidDataValue { field_name: &'static str }, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "The client_secret provided does not match the client_secret associated with the Payment.")] + ClientSecretInvalid, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Customer has existing mandate/subsciption.")] + MandateActive, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Customer has already redacted.")] + CustomerRedacted, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Reached maximum refund attempts")] MaximumRefundCount, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Refund amount exceeds the payment amount.")] + RefundAmountExceedsPaymentAmount, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")] PaymentUnexpectedState { current_flow: String, @@ -61,14 +65,13 @@ pub enum ApiErrorResponse { current_value: String, states: String, }, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Invalid Ephemeral Key for the customer")] + InvalidEphermeralKey, /// Typically used when information involving multiple fields or previously provided /// information doesn't satisfy a condition. #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "{message}")] PreconditionFailed { message: String }, - #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "The client_secret provided does not match the client_secret associated with the Payment.")] - ClientSecretInvalid, - #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed while processing with connector. Retry payment.")] PaymentAuthorizationFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed while processing with connector. Retry payment.")] @@ -168,6 +171,8 @@ impl actix_web::ResponseError for ApiErrorResponse { ApiErrorResponse::DuplicateRefundRequest => StatusCode::BAD_REQUEST, // 400 ApiErrorResponse::RefundNotFound | ApiErrorResponse::CustomerNotFound + | ApiErrorResponse::MandateActive + | ApiErrorResponse::CustomerRedacted | ApiErrorResponse::PaymentNotFound | ApiErrorResponse::PaymentMethodNotFound | ApiErrorResponse::MerchantAccountNotFound diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 862c075346f..20fa547987e 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -198,6 +198,23 @@ pub async fn mock_get_card<'a>( }) } +#[instrument(skip_all)] +pub async fn mock_delete_card<'a>( + db: &dyn db::StorageInterface, + card_id: &'a str, +) -> errors::CustomResult<payment_methods::DeleteCardResponse, errors::CardVaultError> { + let locker_mock_up = db + .delete_locker_mock_up(card_id) + .await + .change_context(errors::CardVaultError::FetchCardFailed)?; + Ok(payment_methods::DeleteCardResponse { + card_id: locker_mock_up.card_id, + external_id: locker_mock_up.external_id, + card_isin: None, + status: "SUCCESS".to_string(), + }) +} + #[instrument(skip_all)] pub async fn get_card_from_legacy_locker<'a>( state: &'a routes::AppState, @@ -238,17 +255,25 @@ pub async fn delete_card<'a>( merchant_id: &'a str, card_id: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResponse> { + let locker = &state.conf.locker; let request = payment_methods::mk_delete_card_request(&state.conf.locker, merchant_id, card_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Making Delete card request Failed")?; // FIXME use call_api 2. Serde's handle should be inside the generic function - let delete_card_resp = services::call_connector_api(state, request) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)? - .map_err(|_x| errors::ApiErrorResponse::InternalServerError)? - .response - .parse_struct("DeleteCardResponse") - .change_context(errors::ApiErrorResponse::InternalServerError)?; + let delete_card_resp = if !locker.mock_locker { + services::call_connector_api(state, request) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)? + .map_err(|_x| errors::ApiErrorResponse::InternalServerError)? + .response + .parse_struct("DeleteCardResponse") + .change_context(errors::ApiErrorResponse::InternalServerError)? + } else { + mock_delete_card(&*state.store, card_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)? + }; + Ok(delete_card_resp) } diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 38a33feaa25..9a763044a20 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -14,14 +14,23 @@ pub trait AddressInterface { address_id: String, address: storage::AddressUpdate, ) -> CustomResult<storage::Address, errors::StorageError>; + async fn insert_address( &self, address: storage::AddressNew, ) -> CustomResult<storage::Address, errors::StorageError>; + async fn find_address( &self, address_id: &str, ) -> CustomResult<storage::Address, errors::StorageError>; + + async fn update_address_by_merchant_id_customer_id( + &self, + customer_id: &str, + merchant_id: &str, + address: storage::AddressUpdate, + ) -> CustomResult<Vec<storage::Address>, errors::StorageError>; } #[async_trait::async_trait] @@ -60,6 +69,24 @@ impl AddressInterface for Store { .map_err(Into::into) .into_report() } + + async fn update_address_by_merchant_id_customer_id( + &self, + customer_id: &str, + merchant_id: &str, + address: storage::AddressUpdate, + ) -> CustomResult<Vec<storage::Address>, errors::StorageError> { + let conn = pg_connection(&self.master_pool).await; + storage::Address::update_by_merchant_id_customer_id( + &conn, + customer_id, + merchant_id, + address, + ) + .await + .map_err(Into::into) + .into_report() + } } #[async_trait::async_trait] @@ -85,4 +112,13 @@ impl AddressInterface for MockDb { ) -> CustomResult<storage::Address, errors::StorageError> { todo!() } + + async fn update_address_by_merchant_id_customer_id( + &self, + _customer_id: &str, + _merchant_id: &str, + _address: storage::AddressUpdate, + ) -> CustomResult<Vec<storage::Address>, errors::StorageError> { + todo!() + } } diff --git a/crates/router/src/db/locker_mock_up.rs b/crates/router/src/db/locker_mock_up.rs index 20da7085452..cc023726348 100644 --- a/crates/router/src/db/locker_mock_up.rs +++ b/crates/router/src/db/locker_mock_up.rs @@ -18,6 +18,11 @@ pub trait LockerMockUpInterface { &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; + + async fn delete_locker_mock_up( + &self, + card_id: &str, + ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; } #[async_trait::async_trait] @@ -40,6 +45,17 @@ impl LockerMockUpInterface for Store { let conn = pg_connection(&self.master_pool).await; new.insert(&conn).await.map_err(Into::into).into_report() } + + async fn delete_locker_mock_up( + &self, + card_id: &str, + ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { + let conn = pg_connection(&self.master_pool).await; + storage::LockerMockUp::delete_by_card_id(&conn, card_id) + .await + .map_err(Into::into) + .into_report() + } } #[async_trait::async_trait] @@ -57,4 +73,11 @@ impl LockerMockUpInterface for MockDb { ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { todo!() } + + async fn delete_locker_mock_up( + &self, + _card_id: &str, + ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { + todo!() + } } diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index b60cb007120..419e4672e62 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -94,7 +94,7 @@ pub async fn customers_delete( &state, &req, payload, - |state, merchant_account, req| delete_customer(&*state.store, merchant_account, req), + delete_customer, api::MerchantAuthentication::ApiKey, ) .await diff --git a/crates/storage_models/src/query/address.rs b/crates/storage_models/src/query/address.rs index 4b9b74cc9fd..b472290b51d 100644 --- a/crates/storage_models/src/query/address.rs +++ b/crates/storage_models/src/query/address.rs @@ -1,4 +1,4 @@ -use diesel::{associations::HasTable, ExpressionMethods}; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use router_env::{tracing, tracing::instrument}; use super::generics::{self, ExecuteQuery}; @@ -61,6 +61,23 @@ impl Address { .await } + pub async fn update_by_merchant_id_customer_id( + conn: &PgPooledConn, + customer_id: &str, + merchant_id: &str, + address: AddressUpdate, + ) -> CustomResult<Vec<Self>, errors::DatabaseError> { + generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, Self, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::customer_id.eq(customer_id.to_owned())), + AddressUpdateInternal::from(address), + ExecuteQuery::new(), + ) + .await + } + #[instrument(skip(conn))] pub async fn find_by_address_id<'a>( conn: &PgPooledConn, diff --git a/crates/storage_models/src/query/locker_mock_up.rs b/crates/storage_models/src/query/locker_mock_up.rs index af0cf1d46b4..a634110bca7 100644 --- a/crates/storage_models/src/query/locker_mock_up.rs +++ b/crates/storage_models/src/query/locker_mock_up.rs @@ -31,4 +31,17 @@ impl LockerMockUp { ) .await } + + #[instrument(skip(conn))] + pub async fn delete_by_card_id( + conn: &PgPooledConn, + card_id: &str, + ) -> CustomResult<Self, errors::DatabaseError> { + generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self, _>( + conn, + dsl::card_id.eq(card_id.to_owned()), + ExecuteQuery::new(), + ) + .await + } }
2022-12-05T08:39:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description GDPR payment regulations state that all businesses that collect/process personal data of customers from Europe need to comply with the regulatory requirements. GDPR protects customers’ privacy by empowering the customer with the ownership of their personal data and thereby enabling them to dictate how their personal data should be handled by those who collected it customer delete call also delete all the data associated with that customer ### Additional Changes - [ ] 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 its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Not tested yet ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [x] I added unit tests for my changes where possible - [x] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6bf99048673c9a8f02dfe6f061226da03fc1aadb
juspay/hyperswitch
juspay__hyperswitch-3267
Bug: Deep health check for Hyperswitch Server Components to be verified in the check: - [x] RDS (PostgreSQL) - Connection to Database - Read check - Write check (v2) - State of Migration (v2) - [x] ElastiCache (Redis) - Connection to Redis - Stream insertions - [x] Locker Connection (/health (deep health check)) - [x] #3518 - Verifying how the pod is able to connect to internet - [x] Clickhouse
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs new file mode 100644 index 00000000000..d7bb120d017 --- /dev/null +++ b/crates/api_models/src/health_check.rs @@ -0,0 +1,6 @@ +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RouterHealthCheckResponse { + pub database: String, + pub redis: String, + pub locker: String, +} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 935944cf74c..459443747e3 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -16,6 +16,7 @@ pub mod errors; pub mod events; pub mod files; pub mod gsm; +pub mod health_check; pub mod locker_migration; pub mod mandates; pub mod organization; diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 4a2d2831d10..eff42c0cd7c 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -70,3 +70,5 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant"; + +pub const LOCKER_HEALTH_CALL_PATH: &str = "/health"; diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 0cd4cb21881..5beace9cbb8 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -14,6 +14,7 @@ pub mod events; pub mod file; pub mod fraud_check; pub mod gsm; +pub mod health_check; mod kafka_store; pub mod locker_mock_up; pub mod mandate; @@ -103,6 +104,7 @@ pub trait StorageInterface: + user_role::UserRoleInterface + authorization::AuthorizationInterface + user::sample_data::BatchSampleDataInterface + + health_check::HealthCheckInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/health_check.rs b/crates/router/src/db/health_check.rs new file mode 100644 index 00000000000..73bc2a4321d --- /dev/null +++ b/crates/router/src/db/health_check.rs @@ -0,0 +1,147 @@ +use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; +use diesel_models::ConfigNew; +use error_stack::ResultExt; +use router_env::logger; + +use super::{MockDb, StorageInterface, Store}; +use crate::{ + connection, + consts::LOCKER_HEALTH_CALL_PATH, + core::errors::{self, CustomResult}, + routes, + services::api as services, + types::storage, +}; + +#[async_trait::async_trait] +pub trait HealthCheckInterface { + async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>; + async fn health_check_redis( + &self, + db: &dyn StorageInterface, + ) -> CustomResult<(), errors::HealthCheckRedisError>; + async fn health_check_locker( + &self, + state: &routes::AppState, + ) -> CustomResult<(), errors::HealthCheckLockerError>; +} + +#[async_trait::async_trait] +impl HealthCheckInterface for Store { + async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { + let conn = connection::pg_connection_write(self) + .await + .change_context(errors::HealthCheckDBError::DBError)?; + + let _data = conn + .transaction_async(|conn| { + Box::pin(async move { + let query = + diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1")); + let _x: i32 = query.get_result_async(&conn).await.map_err(|err| { + logger::error!(read_err=?err,"Error while reading element in the database"); + errors::HealthCheckDBError::DBReadError + })?; + + logger::debug!("Database read was successful"); + + let config = ConfigNew { + key: "test_key".to_string(), + config: "test_value".to_string(), + }; + + config.insert(&conn).await.map_err(|err| { + logger::error!(write_err=?err,"Error while writing to database"); + errors::HealthCheckDBError::DBWriteError + })?; + + logger::debug!("Database write was successful"); + + storage::Config::delete_by_key(&conn, "test_key").await.map_err(|err| { + logger::error!(delete_err=?err,"Error while deleting element in the database"); + errors::HealthCheckDBError::DBDeleteError + })?; + + logger::debug!("Database delete was successful"); + + Ok::<_, errors::HealthCheckDBError>(()) + }) + }) + .await?; + + Ok(()) + } + + async fn health_check_redis( + &self, + db: &dyn StorageInterface, + ) -> CustomResult<(), errors::HealthCheckRedisError> { + let redis_conn = db + .get_redis_conn() + .change_context(errors::HealthCheckRedisError::RedisConnectionError)?; + + redis_conn + .serialize_and_set_key_with_expiry("test_key", "test_value", 30) + .await + .change_context(errors::HealthCheckRedisError::SetFailed)?; + + logger::debug!("Redis set_key was successful"); + + redis_conn + .get_key("test_key") + .await + .change_context(errors::HealthCheckRedisError::GetFailed)?; + + logger::debug!("Redis get_key was successful"); + + redis_conn + .delete_key("test_key") + .await + .change_context(errors::HealthCheckRedisError::DeleteFailed)?; + + logger::debug!("Redis delete_key was successful"); + + Ok(()) + } + + async fn health_check_locker( + &self, + state: &routes::AppState, + ) -> CustomResult<(), errors::HealthCheckLockerError> { + let locker = &state.conf.locker; + if !locker.mock_locker { + let mut url = locker.host_rs.to_owned(); + url.push_str(LOCKER_HEALTH_CALL_PATH); + let request = services::Request::new(services::Method::Get, &url); + services::call_connector_api(state, request) + .await + .change_context(errors::HealthCheckLockerError::FailedToCallLocker)? + .ok(); + } + + logger::debug!("Locker call was successful"); + + Ok(()) + } +} + +#[async_trait::async_trait] +impl HealthCheckInterface for MockDb { + async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { + Ok(()) + } + + async fn health_check_redis( + &self, + _: &dyn StorageInterface, + ) -> CustomResult<(), errors::HealthCheckRedisError> { + Ok(()) + } + + async fn health_check_locker( + &self, + _: &routes::AppState, + ) -> CustomResult<(), errors::HealthCheckLockerError> { + Ok(()) + } +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index db94c1bcbca..1184992a8f7 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -43,6 +43,7 @@ use crate::{ events::EventInterface, file::FileMetadataInterface, gsm::GsmInterface, + health_check::HealthCheckInterface, locker_mock_up::LockerMockUpInterface, mandate::MandateInterface, merchant_account::MerchantAccountInterface, @@ -57,6 +58,7 @@ use crate::{ routing_algorithm::RoutingAlgorithmInterface, MasterKeyInterface, StorageInterface, }, + routes, services::{authentication, kafka::KafkaProducer, Store}, types::{ domain, @@ -2131,3 +2133,24 @@ impl AuthorizationInterface for KafkaStore { .await } } + +#[async_trait::async_trait] +impl HealthCheckInterface for KafkaStore { + async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { + self.diesel_store.health_check_db().await + } + + async fn health_check_redis( + &self, + db: &dyn StorageInterface, + ) -> CustomResult<(), errors::HealthCheckRedisError> { + self.diesel_store.health_check_redis(db).await + } + + async fn health_check_locker( + &self, + state: &routes::AppState, + ) -> CustomResult<(), errors::HealthCheckLockerError> { + self.diesel_store.health_check_locker(state).await + } +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0357cedd443..6625a206be2 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -253,9 +253,10 @@ pub struct Health; impl Health { pub fn server(state: AppState) -> Scope { - web::scope("") + web::scope("health") .app_data(web::Data::new(state)) - .service(web::resource("/health").route(web::get().to(health))) + .service(web::resource("").route(web::get().to(health))) + .service(web::resource("/deep_check").route(web::post().to(deep_health_check))) } } diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index 7c7f29bd181..f07b744f7f5 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -1,7 +1,9 @@ +use actix_web::web; +use api_models::health_check::RouterHealthCheckResponse; use router_env::{instrument, logger, tracing}; -use crate::routes::metrics; - +use super::app; +use crate::{routes::metrics, services}; /// . // #[logger::instrument(skip_all, name = "name1", level = "warn", fields( key1 = "val1" ))] #[instrument(skip_all)] @@ -11,3 +13,59 @@ pub async fn health() -> impl actix_web::Responder { logger::info!("Health was called"); actix_web::HttpResponse::Ok().body("health is good") } + +#[instrument(skip_all)] +pub async fn deep_health_check(state: web::Data<app::AppState>) -> impl actix_web::Responder { + metrics::HEALTH_METRIC.add(&metrics::CONTEXT, 1, &[]); + let db = &*state.store; + let mut status_code = 200; + logger::info!("Deep health check was called"); + + logger::debug!("Database health check begin"); + + let db_status = match db.health_check_db().await { + Ok(_) => "Health is good".to_string(), + Err(err) => { + status_code = 500; + err.to_string() + } + }; + logger::debug!("Database health check end"); + + logger::debug!("Redis health check begin"); + + let redis_status = match db.health_check_redis(db).await { + Ok(_) => "Health is good".to_string(), + Err(err) => { + status_code = 500; + err.to_string() + } + }; + + logger::debug!("Redis health check end"); + + logger::debug!("Locker health check begin"); + + let locker_status = match db.health_check_locker(&state).await { + Ok(_) => "Health is good".to_string(), + Err(err) => { + status_code = 500; + err.to_string() + } + }; + + logger::debug!("Locker health check end"); + + let response = serde_json::to_string(&RouterHealthCheckResponse { + database: db_status, + redis: redis_status, + locker: locker_status, + }) + .unwrap_or_default(); + + if status_code == 200 { + services::http_response_json(response) + } else { + services::http_server_error_json_response(response) + } +} diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 92fda578727..71687e02c12 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1138,6 +1138,14 @@ pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpRe .body(response) } +pub fn http_server_error_json_response<T: body::MessageBody + 'static>( + response: T, +) -> HttpResponse { + HttpResponse::InternalServerError() + .content_type(mime::APPLICATION_JSON) + .body(response) +} + pub fn http_response_json_with_headers<T: body::MessageBody + 'static>( response: T, mut headers: Vec<(String, String)>, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index cc7353dcda6..fca85c41699 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -10,6 +10,7 @@ use router_env::tracing_actix_web::RequestId; use super::{request::Maskable, Request}; use crate::{ configs::settings::{Locker, Proxy}, + consts::LOCKER_HEALTH_CALL_PATH, core::{ errors::{ApiClientError, CustomResult}, payments, @@ -119,6 +120,7 @@ pub fn proxy_bypass_urls(locker: &Locker) -> Vec<String> { format!("{locker_host_rs}/cards/add"), format!("{locker_host_rs}/cards/retrieve"), format!("{locker_host_rs}/cards/delete"), + format!("{locker_host_rs}{}", LOCKER_HEALTH_CALL_PATH), format!("{locker_host}/card/addCard"), format!("{locker_host}/card/getCard"), format!("{locker_host}/card/deleteCard"), diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index f0cbebf78c5..50173bb1c73 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -376,3 +376,53 @@ pub enum ConnectorError { #[error("Missing 3DS redirection payload: {field_name}")] MissingConnectorRedirectionPayload { field_name: &'static str }, } + +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckDBError { + #[error("Error while connecting to database")] + DBError, + #[error("Error while writing to database")] + DBWriteError, + #[error("Error while reading element in the database")] + DBReadError, + #[error("Error while deleting element in the database")] + DBDeleteError, + #[error("Unpredictable error occurred")] + UnknownError, + #[error("Error in database transaction")] + TransactionError, +} + +impl From<diesel::result::Error> for HealthCheckDBError { + fn from(error: diesel::result::Error) -> Self { + match error { + diesel::result::Error::DatabaseError(_, _) => Self::DBError, + + diesel::result::Error::RollbackErrorOnCommit { .. } + | diesel::result::Error::RollbackTransaction + | diesel::result::Error::AlreadyInTransaction + | diesel::result::Error::NotInTransaction + | diesel::result::Error::BrokenTransactionManager => Self::TransactionError, + + _ => Self::UnknownError, + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckRedisError { + #[error("Failed to establish Redis connection")] + RedisConnectionError, + #[error("Failed to set key value in Redis")] + SetFailed, + #[error("Failed to get key value in Redis")] + GetFailed, + #[error("Failed to delete key value in Redis")] + DeleteFailed, +} + +#[derive(Debug, Clone, thiserror::Error)] +pub enum HealthCheckLockerError { + #[error("Failed to establish Locker connection")] + FailedToCallLocker, +}
2023-12-27T15:29:09Z
## 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 support for performing a deeper health check of the application which includes: * Database connection check with read, write and delete queries (Added support for database transaction too) * Redis connection check with set, get and delete key (Set key with expiry of 30sec) * Locker health call from Hyperswitch application The deep health check API returns a 200 status code if all the components are in good health, but returns 500 if at least one component's health is down ### 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. Hit `/health` for getting just the application health. 2. Hit `/health/deep_check` for getting deep report of components health * Test case 1 (Application not able to connect to database because postgresql is down) ![image](https://github.com/juspay/hyperswitch/assets/70657455/5e8af307-0b01-4008-a8e7-30d1aa8d3ed4) * Test case 2 (Database Insert query failing because of duplication) ![image](https://github.com/juspay/hyperswitch/assets/70657455/0775c8db-bf43-4cf1-b197-33dea3b51058) * Test case 3 (Locker is down) ![image](https://github.com/juspay/hyperswitch/assets/70657455/2bc6d734-8da5-4b87-8138-d22ba76a0bc7) * Test case 4 (Locker is up but key custodian locked) ![image](https://github.com/juspay/hyperswitch/assets/70657455/35b83c7a-388f-4128-8913-66f1a8e23bde) * Test case 5 (Locker is up with key custodian unlocked) ![image](https://github.com/juspay/hyperswitch/assets/70657455/ed64322e-08d0-458e-af69-fe8010d21a61) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
72968dcecf16c8821a383a826e4e35408b035633
juspay/hyperswitch
juspay__hyperswitch-3260
Bug: [BUG] WASM build fails on latest pull ### Bug Description The workspace builds ok, but wasm-pack build `wasm-pack build --target web --out-dir "${PWD}/wasm" --out-name euclid crates/euclid_wasm -- --features development,dummy_connector` fails on compilation of mio-0.8.8 ### Expected Behavior build wasm folder correctly ### Actual Behavior Compilation error on mio-0.8.8: ``` [INFO]: 🎯 Checking for the Wasm target... [INFO]: 🌀 Compiling to Wasm... Compiling proc-macro2 v1.0.76 Compiling serde v1.0.195 Compiling once_cell v1.19.0 Compiling memchr v2.7.1 Compiling quote v1.0.35 Compiling syn v2.0.48 Compiling syn v1.0.109 Compiling serde_derive v1.0.195 Compiling itoa v1.0.10 Compiling wasm-bindgen-shared v0.2.89 Compiling futures-core v0.3.30 Compiling wasm-bindgen-backend v0.2.89 Compiling thiserror v1.0.56 Compiling wasm-bindgen-macro-support v0.2.89 Compiling wasm-bindgen v0.2.89 Compiling wasm-bindgen-macro v0.2.89 Compiling thiserror-impl v1.0.56 Compiling smallvec v1.11.2 Compiling futures-sink v0.3.30 Compiling js-sys v0.3.66 Compiling lock_api v0.4.11 Compiling parking_lot_core v0.9.9 Compiling tracing-core v0.1.32 Compiling serde_json v1.0.111 Compiling parking_lot v0.12.1 Compiling futures-channel v0.3.30 Compiling mio v0.8.10 error[E0432]: unresolved import `crate::sys::IoSourceState` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:12:5 | 12 | use crate::sys::IoSourceState; | ^^^^^^^^^^^^^^^^^^^^^^^^^ no `IoSourceState` in `sys` error[E0432]: unresolved import `crate::sys::tcp` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:15:17 | 15 | use crate::sys::tcp::{bind, listen, new_for_addr}; | ^^^ could not find `tcp` in `sys` error[E0432]: unresolved import `crate::sys::tcp` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:13:17 | 13 | use crate::sys::tcp::{connect, new_for_addr}; | ^^^ could not find `tcp` in `sys` error[E0433]: failed to resolve: could not find `Selector` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/poll.rs:312:18 | 312 | sys::Selector::new().map(|selector| Poll { | ^^^^^^^^ could not find `Selector` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:24:14 | 24 | sys::event::token(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:38:14 | 38 | sys::event::is_readable(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:43:14 | 43 | sys::event::is_writable(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:68:14 | 68 | sys::event::is_error(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:99:14 | 99 | sys::event::is_read_closed(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:129:14 | 129 | sys::event::is_write_closed(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:151:14 | 151 | sys::event::is_priority(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:173:14 | 173 | sys::event::is_aio(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:183:14 | 183 | sys::event::is_lio(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:221:26 | 221 | sys::event::debug_details(f, self.0) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `tcp` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:103:18 | 103 | sys::tcp::accept(inner).map(|(stream, addr)| (TcpStream::from_std(stream), addr)) | ^^^ could not find `tcp` in `sys` error[E0433]: failed to resolve: could not find `udp` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:122:14 | 122 | sys::udp::bind(addr).map(UdpSocket::from_std) | ^^^ could not find `udp` in `sys` error[E0433]: failed to resolve: could not find `udp` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:544:14 | 544 | sys::udp::only_v6(&self.inner) | ^^^ could not find `udp` in `sys` error[E0412]: cannot find type `Selector` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/poll.rs:263:20 | 263 | selector: sys::Selector, | ^^^^^^^^ not found in `sys` error[E0412]: cannot find type `Selector` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/poll.rs:710:44 | 710 | pub(crate) fn selector(&self) -> &sys::Selector { | ^^^^^^^^ not found in `sys` error[E0412]: cannot find type `Waker` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/waker.rs:79:17 | 79 | inner: sys::Waker, | ^^^^^ not found in `sys` | help: consider importing one of these items | 1 + use core::task::Waker; | 1 + use crate::Waker; | 1 + use std::task::Waker; | help: if you import `Waker`, refer to it directly | 79 - inner: sys::Waker, 79 + inner: Waker, | error[E0433]: failed to resolve: could not find `Waker` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/waker.rs:87:14 | 87 | sys::Waker::new(registry.selector(), token).map(|inner| Waker { inner }) | ^^^^^ could not find `Waker` in `sys` | help: consider importing one of these items | 1 + use core::task::Waker; | 1 + use crate::Waker; | 1 + use std::task::Waker; | help: if you import `Waker`, refer to it directly | 87 - sys::Waker::new(registry.selector(), token).map(|inner| Waker { inner }) 87 + Waker::new(registry.selector(), token).map(|inner| Waker { inner }) | error[E0412]: cannot find type `Event` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:18:17 | 18 | inner: sys::Event, | ^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::event::Event; | help: if you import `Event`, refer to it directly | 18 - inner: sys::Event, 18 + inner: Event, | error[E0412]: cannot find type `Event` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:187:55 | 187 | pub(crate) fn from_sys_event_ref(sys_event: &sys::Event) -> &Event { | ^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::event::Event; | help: if you import `Event`, refer to it directly | 187 - pub(crate) fn from_sys_event_ref(sys_event: &sys::Event) -> &Event { 187 + pub(crate) fn from_sys_event_ref(sys_event: &Event) -> &Event { | error[E0412]: cannot find type `Event` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:191:41 | 191 | &*(sys_event as *const sys::Event as *const Event) | ^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::event::Event; | help: if you import `Event`, refer to it directly | 191 - &*(sys_event as *const sys::Event as *const Event) 191 + &*(sys_event as *const Event as *const Event) | error[E0412]: cannot find type `Event` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:217:46 | 217 | struct EventDetails<'a>(&'a sys::Event); | ^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::event::Event; | help: if you import `Event`, refer to it directly | 217 - struct EventDetails<'a>(&'a sys::Event); 217 + struct EventDetails<'a>(&'a Event); | error[E0412]: cannot find type `Events` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/events.rs:43:17 | 43 | inner: sys::Events, | ^^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::Events; | help: if you import `Events`, refer to it directly | 43 - inner: sys::Events, 43 + inner: Events, | error[E0433]: failed to resolve: could not find `Events` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/events.rs:94:25 | 94 | inner: sys::Events::with_capacity(capacity), | ^^^^^^ could not find `Events` in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::Events; | help: if you import `Events`, refer to it directly | 94 - inner: sys::Events::with_capacity(capacity), 94 + inner: Events::with_capacity(capacity), | error[E0412]: cannot find type `Events` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/events.rs:189:47 | 189 | pub(crate) fn sys(&mut self) -> &mut sys::Events { | ^^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::Events; | help: if you import `Events`, refer to it directly | 189 - pub(crate) fn sys(&mut self) -> &mut sys::Events { 189 + pub(crate) fn sys(&mut self) -> &mut Events { | error[E0425]: cannot find value `listener` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:74:24 | 74 | set_reuseaddr(&listener.inner, true)?; | ^^^^^^^^ not found in this scope error[E0425]: cannot find value `listener` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:76:15 | 76 | bind(&listener.inner, addr)?; | ^^^^^^^^ not found in this scope error[E0425]: cannot find value `listener` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:77:17 | 77 | listen(&listener.inner, 1024)?; | ^^^^^^^^ not found in this scope error[E0425]: cannot find value `listener` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:78:12 | 78 | Ok(listener) | ^^^^^^^^ not found in this scope error[E0425]: cannot find value `stream` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:90:18 | 90 | connect(&stream.inner, addr)?; | ^^^^^^ not found in this scope error[E0425]: cannot find value `stream` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:91:12 | 91 | Ok(stream) | ^^^^^^ not found in this scope error[E0425]: cannot find function `set_reuseaddr` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:74:9 | 74 | set_reuseaddr(&listener.inner, true)?; | ^^^^^^^^^^^^^ not found in this scope error[E0599]: no method named `register` found for struct `IoSource<std::net::TcpListener>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:146:20 | 146 | self.inner.register(registry, token, interests) | ^^^^^^^^ method not found in `IoSource<TcpListener>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `register` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `register`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `reregister` found for struct `IoSource<std::net::TcpListener>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:155:20 | 155 | self.inner.reregister(registry, token, interests) | ^^^^^^^^^^ method not found in `IoSource<TcpListener>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `reregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `reregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `deregister` found for struct `IoSource<std::net::TcpListener>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:159:20 | 159 | self.inner.deregister(registry) | ^^^^^^^^^^ method not found in `IoSource<TcpListener>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `deregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `deregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `register` found for struct `IoSource<std::net::TcpStream>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:325:20 | 325 | self.inner.register(registry, token, interests) | ^^^^^^^^ method not found in `IoSource<TcpStream>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `register` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `register`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `reregister` found for struct `IoSource<std::net::TcpStream>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:334:20 | 334 | self.inner.reregister(registry, token, interests) | ^^^^^^^^^^ method not found in `IoSource<TcpStream>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `reregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `reregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `deregister` found for struct `IoSource<std::net::TcpStream>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:338:20 | 338 | self.inner.deregister(registry) | ^^^^^^^^^^ method not found in `IoSource<TcpStream>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `deregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `deregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `register` found for struct `IoSource<std::net::UdpSocket>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:622:20 | 622 | self.inner.register(registry, token, interests) | ^^^^^^^^ method not found in `IoSource<UdpSocket>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `register` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `register`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `reregister` found for struct `IoSource<std::net::UdpSocket>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:631:20 | 631 | self.inner.reregister(registry, token, interests) | ^^^^^^^^^^ method not found in `IoSource<UdpSocket>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `reregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `reregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `deregister` found for struct `IoSource<std::net::UdpSocket>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:635:20 | 635 | self.inner.deregister(registry) | ^^^^^^^^^^ method not found in `IoSource<UdpSocket>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `deregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `deregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ Some errors have detailed explanations: E0412, E0425, E0432, E0433, E0599. For more information about an error, try `rustc --explain E0412`. error: could not compile `mio` (lib) due to 44 previous errors warning: build failed, waiting for other jobs to finish... Error: Compiling your crate to WebAssembly failed Caused by: Compiling your crate to WebAssembly failed Caused by: failed to execute `cargo build`: exited with exit status: 101 full command: cd "crates/euclid_wasm" && "cargo" "build" "--lib" "--release" "--target" "wasm32-unknown-unknown" "--features" "development,dummy_connector" ``` ### Steps To Reproduce wasm-pack build --target web --out-dir "${PWD}/wasm" --out-name euclid crates/euclid_wasm -- --features development,dummy_connector ### Context For The Bug _No response_ ### Environment Self-hosted sandbox 1. Operating system: Ubuntu 22.04 2. Rust version (output of `rustc --version`): `1.75` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml index cf3e25459c6..6892350ce6f 100644 --- a/crates/cards/Cargo.toml +++ b/crates/cards/Cargo.toml @@ -19,6 +19,8 @@ time = "0.3.21" # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } masking = { version = "0.1.0", path = "../masking" } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } [dev-dependencies] diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index 001eab3004d..ca47c73c7c2 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -1,6 +1,7 @@ use std::{fmt, ops::Deref, str::FromStr}; use masking::{PeekInterface, Strategy, StrongSecret, WithType}; +#[cfg(not(target_arch = "wasm32"))] use router_env::logger; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; @@ -89,6 +90,7 @@ where if let Some(value) = val_str.get(..6) { write!(f, "{}{}", value, "*".repeat(val_str.len() - 6)) } else { + #[cfg(not(target_arch = "wasm32"))] logger::error!("Invalid card number {val_str}"); WithType::fmt(val, f) }
2024-01-08T17:33:58Z
## 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 PR fixes failing `wasm-pack build` for the `euclid_wasm` crate. ### 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). --> Fixes #3260. ## 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="1242" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3d7203ad-c50d-428e-9ec9-d05248c398bd"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5484cf42426d37667266fb952b800a6dab5e305e
juspay/hyperswitch
juspay__hyperswitch-3268
Bug: Deep health check for Hyperswitch Scheduler Components to be verified in the check: - [x] RDS (PostgreSQL) - Connection to Database - State of Migration - [x] ElastiCache (Redis) - Connection to Redis - [x] Stream Insertion - [x] #3524 - [x] Clickhouse
diff --git a/Cargo.lock b/Cargo.lock index a1aabc89a04..f0334ce9cfc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5526,6 +5526,7 @@ dependencies = [ "external_services", "futures 0.3.28", "masking", + "num_cpus", "once_cell", "rand 0.8.5", "redis_interface", diff --git a/config/config.example.toml b/config/config.example.toml index f7e9fa70f6e..fc5d4a3a039 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -298,6 +298,12 @@ lower_fetch_limit = 1800 # Lower limit for fetching entries from redis lock_key = "PRODUCER_LOCKING_KEY" # The following keys defines the producer lock that is created in redis with lock_ttl = 160 # the ttl being the expiry (in seconds) +# Scheduler server configuration +[scheduler.server] +port = 3000 # Port on which the server will listen for incoming requests +host = "127.0.0.1" # Host IP address to bind the server to +workers = 1 # Number of actix workers to handle incoming requests concurrently + batch_size = 200 # Specifies the batch size the producer will push under a single entry in the redis queue # Drainer configuration, which handles draining raw SQL queries from Redis streams to the SQL database diff --git a/config/deployments/scheduler/consumer.toml b/config/deployments/scheduler/consumer.toml index 907e3b8297e..cdd60552668 100644 --- a/config/deployments/scheduler/consumer.toml +++ b/config/deployments/scheduler/consumer.toml @@ -9,3 +9,9 @@ stream = "scheduler_stream" [scheduler.consumer] consumer_group = "scheduler_group" disabled = false # This flag decides if the consumer should actively consume task + +# Scheduler server configuration +[scheduler.server] +port = 3000 # Port on which the server will listen for incoming requests +host = "127.0.0.1" # Host IP address to bind the server to +workers = 1 # Number of actix workers to handle incoming requests concurrently diff --git a/config/deployments/scheduler/producer.toml b/config/deployments/scheduler/producer.toml index 579466a23cc..9cbaee96f03 100644 --- a/config/deployments/scheduler/producer.toml +++ b/config/deployments/scheduler/producer.toml @@ -12,3 +12,9 @@ lock_key = "producer_locking_key" # The following keys defines the producer lock lock_ttl = 160 # the ttl being the expiry (in seconds) lower_fetch_limit = 900 # Lower limit for fetching entries from redis queue (in seconds) upper_fetch_limit = 0 # Upper limit for fetching entries from the redis queue (in seconds)0 + +# Scheduler server configuration +[scheduler.server] +port = 3000 # Port on which the server will listen for incoming requests +host = "127.0.0.1" # Host IP address to bind the server to +workers = 1 # Number of actix workers to handle incoming requests concurrently diff --git a/config/development.toml b/config/development.toml index 584bdf751a2..20abb7bd6f3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -228,6 +228,11 @@ stream = "SCHEDULER_STREAM" disabled = false consumer_group = "SCHEDULER_GROUP" +[scheduler.server] +port = 3000 +host = "127.0.0.1" +workers = 1 + [email] sender_email = "example@example.com" aws_region = "" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 67fca85929d..d14b7c1b740 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -227,6 +227,11 @@ stream = "SCHEDULER_STREAM" disabled = false consumer_group = "SCHEDULER_GROUP" +[scheduler.server] +port = 3000 +host = "127.0.0.1" +workers = 1 + #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index 8323f135134..eab971b5fe1 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -8,3 +8,10 @@ pub struct RouterHealthCheckResponse { } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SchedulerHealthCheckResponse { + pub database: bool, + pub redis: bool, +} + +impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {} diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index b800ecb897e..5f98cd88014 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -1,21 +1,29 @@ #![recursion_limit = "256"] use std::{str::FromStr, sync::Arc}; +use actix_web::{dev::Server, web, Scope}; +use api_models::health_check::SchedulerHealthCheckResponse; use common_utils::ext_traits::{OptionExt, StringExt}; use diesel_models::process_tracker as storage; use error_stack::ResultExt; use router::{ configs::settings::{CmdLineConf, Settings}, - core::errors::{self, CustomResult}, - logger, routes, services, + core::{ + errors::{self, CustomResult}, + health_check::HealthCheckInterface, + }, + logger, routes, + services::{self, api}, types::storage::ProcessTrackerExt, workflows, }; +use router_env::{instrument, tracing}; use scheduler::{ consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError, workflows::ProcessTrackerWorkflows, SchedulerAppState, }; use serde::{Deserialize, Serialize}; +use storage_impl::errors::ApplicationError; use strum::EnumString; use tokio::sync::{mpsc, oneshot}; @@ -68,6 +76,19 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { [router_env::service_name!()], ); + #[allow(clippy::expect_used)] + let web_server = Box::pin(start_web_server( + state.clone(), + scheduler_flow_str.to_string(), + )) + .await + .expect("Failed to create the server"); + + tokio::spawn(async move { + let _ = web_server.await; + logger::error!("The health check probe stopped working!"); + }); + logger::debug!(startup_config=?state.conf); start_scheduler(&state, scheduler_flow, (tx, rx)).await?; @@ -76,6 +97,106 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { Ok(()) } +pub async fn start_web_server( + state: routes::AppState, + service: String, +) -> errors::ApplicationResult<Server> { + let server = state + .conf + .scheduler + .as_ref() + .ok_or(ApplicationError::InvalidConfigurationValueError( + "Scheduler server is invalidly configured".into(), + ))? + .server + .clone(); + + let web_server = actix_web::HttpServer::new(move || { + actix_web::App::new().service(Health::server(state.clone(), service.clone())) + }) + .bind((server.host.as_str(), server.port))? + .workers(server.workers) + .run(); + let _ = web_server.handle(); + + Ok(web_server) +} + +pub struct Health; + +impl Health { + pub fn server(state: routes::AppState, service: String) -> Scope { + web::scope("health") + .app_data(web::Data::new(state)) + .app_data(web::Data::new(service)) + .service(web::resource("").route(web::get().to(health))) + .service(web::resource("/ready").route(web::get().to(deep_health_check))) + } +} + +#[instrument(skip_all)] +pub async fn health() -> impl actix_web::Responder { + logger::info!("Scheduler health was called"); + actix_web::HttpResponse::Ok().body("Scheduler health is good") +} +#[instrument(skip_all)] +pub async fn deep_health_check( + state: web::Data<routes::AppState>, + service: web::Data<String>, +) -> impl actix_web::Responder { + let report = deep_health_check_func(state, service).await; + match report { + Ok(response) => services::http_response_json( + serde_json::to_string(&response) + .map_err(|err| { + logger::error!(serialization_error=?err); + }) + .unwrap_or_default(), + ), + Err(err) => api::log_and_return_error_response(err), + } +} +#[instrument(skip_all)] +pub async fn deep_health_check_func( + state: web::Data<routes::AppState>, + service: web::Data<String>, +) -> errors::RouterResult<SchedulerHealthCheckResponse> { + logger::info!("{} deep health check was called", service.into_inner()); + + logger::debug!("Database health check begin"); + + let db_status = state.health_check_db().await.map(|_| true).map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Database", + message: err.to_string() + }) + })?; + + logger::debug!("Database health check end"); + + logger::debug!("Redis health check begin"); + + let redis_status = state + .health_check_redis() + .await + .map(|_| true) + .map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Redis", + message: err.to_string() + }) + })?; + + logger::debug!("Redis health check end"); + + let response = SchedulerHealthCheckResponse { + database: db_status, + redis: redis_status, + }; + + Ok(response) +} + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, EnumString)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 023e1f4b7fb..e83483b0816 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -238,7 +238,7 @@ pub enum ApiErrorResponse { WebhookInvalidMerchantSecret, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")] CurrencyNotSupported { message: String }, - #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failiing with error: {message}")] + #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")] HealthCheckError { component: &'static str, message: String, diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index fe090552edb..7d4a7821fc9 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -13,6 +13,7 @@ kv_store = [] async-trait = "0.1.68" error-stack = "0.3.1" futures = "0.3.28" +num_cpus = "1.15.0" once_cell = "1.18.0" rand = "0.8.5" serde = "1.0.193" diff --git a/crates/scheduler/src/configs/defaults.rs b/crates/scheduler/src/configs/defaults.rs index 25eb19e24f2..d17c20829ea 100644 --- a/crates/scheduler/src/configs/defaults.rs +++ b/crates/scheduler/src/configs/defaults.rs @@ -6,6 +6,7 @@ impl Default for super::settings::SchedulerSettings { consumer: super::settings::ConsumerSettings::default(), graceful_shutdown_interval: 60000, loop_interval: 5000, + server: super::settings::Server::default(), } } } @@ -30,3 +31,13 @@ impl Default for super::settings::ConsumerSettings { } } } + +impl Default for super::settings::Server { + fn default() -> Self { + Self { + port: 8080, + workers: num_cpus::get_physical(), + host: "localhost".into(), + } + } +} diff --git a/crates/scheduler/src/configs/settings.rs b/crates/scheduler/src/configs/settings.rs index 56a9f4079ac..723ef81e70c 100644 --- a/crates/scheduler/src/configs/settings.rs +++ b/crates/scheduler/src/configs/settings.rs @@ -15,6 +15,15 @@ pub struct SchedulerSettings { pub consumer: ConsumerSettings, pub loop_interval: u64, pub graceful_shutdown_interval: u64, + pub server: Server, +} + +#[derive(Debug, Deserialize, Clone)] +#[serde(default)] +pub struct Server { + pub port: u16, + pub workers: usize, + pub host: String, } #[derive(Debug, Clone, Deserialize)] diff --git a/crates/scheduler/src/configs/validations.rs b/crates/scheduler/src/configs/validations.rs index e9f6621b2a5..06052f9ff6c 100644 --- a/crates/scheduler/src/configs/validations.rs +++ b/crates/scheduler/src/configs/validations.rs @@ -19,6 +19,8 @@ impl super::settings::SchedulerSettings { self.producer.validate()?; + self.server.validate()?; + Ok(()) } } @@ -32,3 +34,13 @@ impl super::settings::ProducerSettings { }) } } + +impl super::settings::Server { + pub fn validate(&self) -> Result<(), ApplicationError> { + common_utils::fp_utils::when(self.host.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "server host must not be empty".into(), + )) + }) + } +}
2024-01-10T10:08:09Z
## 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 support for performing a deeper health check of the scheduler which includes: Database connection check with read, write and delete queries (Added support for database transaction too) Redis connection check with set, get and delete key (Set key with expiry of 30sec) The deep health check API returns a 200 status code if all the components are in good health, but returns 500 if at least one component's health is down ### 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. `/health` ![image](https://github.com/juspay/hyperswitch/assets/70657455/fe87da30-d4ce-424d-9263-ad76a901f90f) 2. `/health/ready` ![image](https://github.com/juspay/hyperswitch/assets/70657455/922b18b9-006e-403f-93e7-714791c7434b) 3. `'health/ready` with some db error ![image](https://github.com/juspay/hyperswitch/assets/70657455/8def285d-dac3-4804-a7a6-1d67481b1ed0) Cannot be tested on sandbox as the endpoint is not exposed ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
20efc3020ac389199eed13154f070685417ef82a
juspay/hyperswitch
juspay__hyperswitch-3269
Bug: Deep health check for Hyperswitch Drainer Components to be verified in this check - [x] RDS (PostgreSQL) - Connection to Database - State of Migration - [x] ElastiCache (Redis) - Connection to Redis
diff --git a/Cargo.lock b/Cargo.lock index f0334ce9cfc..49ccfc2c645 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2331,6 +2331,7 @@ checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" name = "drainer" version = "0.1.0" dependencies = [ + "actix-web", "async-bb8-diesel", "async-trait", "bb8", @@ -2342,8 +2343,10 @@ dependencies = [ "error-stack", "external_services", "masking", + "mime", "once_cell", "redis_interface", + "reqwest", "router_env", "serde", "serde_json", diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index e4611f43bcf..a8f3db11e39 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -9,6 +9,7 @@ pub struct RouterHealthCheckResponse { } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SchedulerHealthCheckResponse { pub database: bool, diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 67169a15104..0533bd12dab 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -14,13 +14,16 @@ hashicorp-vault = ["external_services/hashicorp-vault"] vergen = ["router_env/vergen"] [dependencies] +actix-web = "4.3.1" async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } bb8 = "0.8" clap = { version = "4.3.2", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.13.3", features = ["toml"] } diesel = { version = "2.1.0", features = ["postgres"] } error-stack = "0.3.1" +mime = "0.3.17" once_cell = "1.18.0" +reqwest = { version = "0.11.18" } serde = "1.0.193" serde_json = "1.0.108" serde_path_to_error = "0.1.14" diff --git a/crates/drainer/src/errors.rs b/crates/drainer/src/errors.rs index 3034e849f8a..8605ee2ba04 100644 --- a/crates/drainer/src/errors.rs +++ b/crates/drainer/src/errors.rs @@ -15,6 +15,22 @@ pub enum DrainerError { ParsingError(error_stack::Report<common_utils::errors::ParsingError>), #[error("Unexpected error occurred: {0}")] UnexpectedError(String), + #[error("I/O: {0}")] + IoError(std::io::Error), +} + +#[derive(Debug, Error, Clone, serde::Serialize)] +pub enum HealthCheckError { + #[error("Database health check is failing with error: {message}")] + DbError { message: String }, + #[error("Redis health check is failing with error: {message}")] + RedisError { message: String }, +} + +impl From<std::io::Error> for DrainerError { + fn from(err: std::io::Error) -> Self { + Self::IoError(err) + } } pub type DrainerResult<T> = error_stack::Result<T, DrainerError>; @@ -30,3 +46,13 @@ impl From<error_stack::Report<redis::errors::RedisError>> for DrainerError { Self::RedisError(err) } } + +impl actix_web::ResponseError for HealthCheckError { + fn status_code(&self) -> reqwest::StatusCode { + use reqwest::StatusCode; + + match self { + Self::DbError { .. } | Self::RedisError { .. } => StatusCode::INTERNAL_SERVER_ERROR, + } + } +} diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs new file mode 100644 index 00000000000..33b4a1395a8 --- /dev/null +++ b/crates/drainer/src/health_check.rs @@ -0,0 +1,268 @@ +use std::sync::Arc; + +use actix_web::{web, Scope}; +use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; +use common_utils::errors::CustomResult; +use diesel_models::{Config, ConfigNew}; +use error_stack::ResultExt; +use router_env::{instrument, logger, tracing}; + +use crate::{ + connection::{pg_connection, redis_connection}, + errors::HealthCheckError, + services::{self, Store}, + settings::Settings, +}; + +pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0"; +pub const TEST_STREAM_DATA: &[(&str, &str)] = &[("data", "sample_data")]; + +pub struct Health; + +impl Health { + pub fn server(conf: Settings, store: Arc<Store>) -> Scope { + web::scope("health") + .app_data(web::Data::new(conf)) + .app_data(web::Data::new(store)) + .service(web::resource("").route(web::get().to(health))) + .service(web::resource("/ready").route(web::get().to(deep_health_check))) + } +} + +#[instrument(skip_all)] +pub async fn health() -> impl actix_web::Responder { + logger::info!("Drainer health was called"); + actix_web::HttpResponse::Ok().body("Drainer health is good") +} + +#[instrument(skip_all)] +pub async fn deep_health_check( + conf: web::Data<Settings>, + store: web::Data<Arc<Store>>, +) -> impl actix_web::Responder { + match deep_health_check_func(conf, store).await { + Ok(response) => services::http_response_json( + serde_json::to_string(&response) + .map_err(|err| { + logger::error!(serialization_error=?err); + }) + .unwrap_or_default(), + ), + + Err(err) => services::log_and_return_error_response(err), + } +} + +#[instrument(skip_all)] +pub async fn deep_health_check_func( + conf: web::Data<Settings>, + store: web::Data<Arc<Store>>, +) -> Result<DrainerHealthCheckResponse, error_stack::Report<HealthCheckError>> { + logger::info!("Deep health check was called"); + + logger::debug!("Database health check begin"); + + let db_status = store.health_check_db().await.map(|_| true).map_err(|err| { + error_stack::report!(HealthCheckError::DbError { + message: err.to_string() + }) + })?; + + logger::debug!("Database health check end"); + + logger::debug!("Redis health check begin"); + + let redis_status = store + .health_check_redis(&conf.into_inner()) + .await + .map(|_| true) + .map_err(|err| { + error_stack::report!(HealthCheckError::RedisError { + message: err.to_string() + }) + })?; + + logger::debug!("Redis health check end"); + + Ok(DrainerHealthCheckResponse { + database: db_status, + redis: redis_status, + }) +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct DrainerHealthCheckResponse { + pub database: bool, + pub redis: bool, +} + +#[async_trait::async_trait] +pub trait HealthCheckInterface { + async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError>; + async fn health_check_redis(&self, conf: &Settings) -> CustomResult<(), HealthCheckRedisError>; +} + +#[async_trait::async_trait] +impl HealthCheckInterface for Store { + async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError> { + let conn = pg_connection(&self.master_pool).await; + + conn + .transaction_async(|conn| { + Box::pin(async move { + let query = + diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1")); + let _x: i32 = query.get_result_async(&conn).await.map_err(|err| { + logger::error!(read_err=?err,"Error while reading element in the database"); + HealthCheckDBError::DbReadError + })?; + + logger::debug!("Database read was successful"); + + let config = ConfigNew { + key: "test_key".to_string(), + config: "test_value".to_string(), + }; + + config.insert(&conn).await.map_err(|err| { + logger::error!(write_err=?err,"Error while writing to database"); + HealthCheckDBError::DbWriteError + })?; + + logger::debug!("Database write was successful"); + + Config::delete_by_key(&conn, "test_key").await.map_err(|err| { + logger::error!(delete_err=?err,"Error while deleting element in the database"); + HealthCheckDBError::DbDeleteError + })?; + + logger::debug!("Database delete was successful"); + + Ok::<_, HealthCheckDBError>(()) + }) + }) + .await?; + + Ok(()) + } + + async fn health_check_redis(&self, conf: &Settings) -> CustomResult<(), HealthCheckRedisError> { + let redis_conn = redis_connection(conf).await; + + redis_conn + .serialize_and_set_key_with_expiry("test_key", "test_value", 30) + .await + .change_context(HealthCheckRedisError::SetFailed)?; + + logger::debug!("Redis set_key was successful"); + + redis_conn + .get_key("test_key") + .await + .change_context(HealthCheckRedisError::GetFailed)?; + + logger::debug!("Redis get_key was successful"); + + redis_conn + .delete_key("test_key") + .await + .change_context(HealthCheckRedisError::DeleteFailed)?; + + logger::debug!("Redis delete_key was successful"); + + redis_conn + .stream_append_entry( + TEST_STREAM_NAME, + &redis_interface::RedisEntryId::AutoGeneratedID, + TEST_STREAM_DATA.to_vec(), + ) + .await + .change_context(HealthCheckRedisError::StreamAppendFailed)?; + + logger::debug!("Stream append succeeded"); + + let output = self + .redis_conn + .stream_read_entries(TEST_STREAM_NAME, "0-0", Some(10)) + .await + .change_context(HealthCheckRedisError::StreamReadFailed)?; + logger::debug!("Stream read succeeded"); + + let (_, id_to_trim) = output + .get(TEST_STREAM_NAME) + .and_then(|entries| { + entries + .last() + .map(|last_entry| (entries, last_entry.0.clone())) + }) + .ok_or(error_stack::report!( + HealthCheckRedisError::StreamReadFailed + ))?; + logger::debug!("Stream parse succeeded"); + + redis_conn + .stream_trim_entries( + TEST_STREAM_NAME, + ( + redis_interface::StreamCapKind::MinID, + redis_interface::StreamCapTrim::Exact, + id_to_trim, + ), + ) + .await + .change_context(HealthCheckRedisError::StreamTrimFailed)?; + logger::debug!("Stream trim succeeded"); + + Ok(()) + } +} + +#[allow(clippy::enum_variant_names)] +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckDBError { + #[error("Error while connecting to database")] + DbError, + #[error("Error while writing to database")] + DbWriteError, + #[error("Error while reading element in the database")] + DbReadError, + #[error("Error while deleting element in the database")] + DbDeleteError, + #[error("Unpredictable error occurred")] + UnknownError, + #[error("Error in database transaction")] + TransactionError, +} + +impl From<diesel::result::Error> for HealthCheckDBError { + fn from(error: diesel::result::Error) -> Self { + match error { + diesel::result::Error::DatabaseError(_, _) => Self::DbError, + + diesel::result::Error::RollbackErrorOnCommit { .. } + | diesel::result::Error::RollbackTransaction + | diesel::result::Error::AlreadyInTransaction + | diesel::result::Error::NotInTransaction + | diesel::result::Error::BrokenTransactionManager => Self::TransactionError, + + _ => Self::UnknownError, + } + } +} + +#[allow(clippy::enum_variant_names)] +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckRedisError { + #[error("Failed to set key value in Redis")] + SetFailed, + #[error("Failed to get key value in Redis")] + GetFailed, + #[error("Failed to delete key value in Redis")] + DeleteFailed, + #[error("Failed to append data to the stream in Redis")] + StreamAppendFailed, + #[error("Failed to read data from the stream in Redis")] + StreamReadFailed, + #[error("Failed to trim data from the stream in Redis")] + StreamTrimFailed, +} diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index abb32c87796..909ae065e26 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -1,6 +1,7 @@ mod connection; pub mod errors; mod handler; +mod health_check; pub mod logger; pub(crate) mod metrics; mod query; @@ -11,6 +12,7 @@ mod types; mod utils; use std::sync::Arc; +use actix_web::dev::Server; use common_utils::signals::get_allowed_signals; use diesel_models::kv; use error_stack::{IntoReport, ResultExt}; @@ -18,7 +20,10 @@ use router_env::{instrument, tracing}; use tokio::sync::mpsc; use crate::{ - connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData, + connection::pg_connection, + services::Store, + settings::{DrainerSettings, Settings}, + types::StreamData, }; pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors::DrainerResult<()> { @@ -49,3 +54,18 @@ pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors:: Ok(()) } + +pub async fn start_web_server( + conf: Settings, + store: Arc<Store>, +) -> Result<Server, errors::DrainerError> { + let server = conf.server.clone(); + let web_server = actix_web::HttpServer::new(move || { + actix_web::App::new().service(health_check::Health::server(conf.clone(), store.clone())) + }) + .bind((server.host.as_str(), server.port))? + .run(); + let _ = web_server.handle(); + + Ok(web_server) +} diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs index 34c1294d55f..943a66f6791 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -1,4 +1,7 @@ -use drainer::{errors::DrainerResult, logger::logger, services, settings, start_drainer}; +use drainer::{ + errors::DrainerResult, logger::logger, services, settings, start_drainer, start_web_server, +}; +use router_env::tracing::Instrument; #[tokio::main] async fn main() -> DrainerResult<()> { @@ -24,6 +27,19 @@ async fn main() -> DrainerResult<()> { [router_env::service_name!()], ); + #[allow(clippy::expect_used)] + let web_server = Box::pin(start_web_server(conf.clone(), store.clone())) + .await + .expect("Failed to create the server"); + + tokio::spawn( + async move { + let _ = web_server.await; + logger::error!("The health check probe stopped working!"); + } + .in_current_span(), + ); + logger::debug!(startup_config=?conf); logger::info!("Drainer started [{:?}] [{:?}]", conf.drainer, conf.log); diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 4393ebb9dc9..0d0b78c0cc6 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -1,6 +1,12 @@ use std::sync::Arc; -use crate::connection::{diesel_make_pg_pool, PgPool}; +use actix_web::{body, HttpResponse, ResponseError}; +use error_stack::Report; + +use crate::{ + connection::{diesel_make_pg_pool, PgPool}, + logger, +}; #[derive(Clone)] pub struct Store { @@ -45,3 +51,23 @@ impl Store { } } } + +pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse +where + T: error_stack::Context + ResponseError + Clone, +{ + logger::error!(?error); + let body = serde_json::json!({ + "message": error.to_string() + }) + .to_string(); + HttpResponse::InternalServerError() + .content_type(mime::APPLICATION_JSON) + .body(body) +} + +pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse { + HttpResponse::Ok() + .content_type(mime::APPLICATION_JSON) + .body(response) +} diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 5b80ee375f5..49cb5f4c7c2 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -30,6 +30,7 @@ pub struct CmdLineConf { #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Settings { + pub server: Server, pub master_database: Database, pub redis: redis::RedisSettings, pub log: Log, @@ -62,6 +63,24 @@ pub struct DrainerSettings { pub loop_interval: u32, // in milliseconds } +#[derive(Debug, Deserialize, Clone)] +#[serde(default)] +pub struct Server { + pub port: u16, + pub workers: usize, + pub host: String, +} + +impl Server { + pub fn validate(&self) -> Result<(), errors::DrainerError> { + common_utils::fp_utils::when(self.host.is_default_or_empty(), || { + Err(errors::DrainerError::ConfigParsingError( + "server host must not be empty".into(), + )) + }) + } +} + impl Default for Database { fn default() -> Self { Self { @@ -88,6 +107,16 @@ impl Default for DrainerSettings { } } +impl Default for Server { + fn default() -> Self { + Self { + host: "127.0.0.1".to_string(), + port: 8080, + workers: 1, + } + } +} + impl Database { fn validate(&self) -> Result<(), errors::DrainerError> { use common_utils::fp_utils::when; @@ -169,6 +198,7 @@ impl Settings { } pub fn validate(&self) -> Result<(), errors::DrainerError> { + self.server.validate()?; self.master_database.validate()?; self.redis.validate().map_err(|error| { println!("{error}");
2024-01-18T18:14:31Z
## 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 support for performing a deeper health check of the drainer which includes: Database connection check with read, write and delete queries (Added support for database transaction too) Redis connection check with set, get and delete key (Set key with expiry of 30sec) The deep health check API returns a 200 status code if all the components are in good health, but returns 500 if at least one component's health is down ### 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. `/health` ![image](https://github.com/juspay/hyperswitch/assets/70657455/d7784ea7-7d21-426f-ba65-69a0f559356e) 2. `/health/deep_check` ![image](https://github.com/juspay/hyperswitch/assets/70657455/aada988f-0058-48af-8654-1070bd810a29) **THIS CANNOT BE TESTED ON SANBOX AS THE ENDPOINT IS NOT EXPOSED** ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
892b04f805c219e2cf7cbe5736aef19909e986f7
juspay/hyperswitch
juspay__hyperswitch-3263
Bug: [FEATURE] : [Connector] Implement Revoke Mandate Flow ### Feature Description When revoke-mandate endpoint is triggered, the mandate should be revoked with connector also. Currently it is being revoked only at core level which is a feature gap. ### Possible Implementation Add a `execute_connector_processing_step` and a flow to revoke the mandate at connector level ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 035f7adec9f..5c0810dc21b 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -17,6 +17,12 @@ pub struct MandateRevokedResponse { /// The status for mandates #[schema(value_type = MandateStatus)] pub status: api_enums::MandateStatus, + /// If there was an error while calling the connectors the code is received here + #[schema(example = "E0001")] + pub error_code: Option<String>, + /// If there was an error while calling the connector the error message is received here + #[schema(example = "Failed while verifying the card")] + pub error_message: Option<String>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 3496f2483ab..33503102e4b 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -55,6 +55,7 @@ impl Cybersource { } = auth; let is_post_method = matches!(http_method, services::Method::Post); let is_patch_method = matches!(http_method, services::Method::Patch); + let is_delete_method = matches!(http_method, services::Method::Delete); let digest_str = if is_post_method || is_patch_method { "digest " } else { @@ -65,6 +66,8 @@ impl Cybersource { format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n") } else if is_patch_method { format!("(request-target): patch {resource}\ndigest: SHA-256={payload}\n") + } else if is_delete_method { + format!("(request-target): delete {resource}\n") } else { format!("(request-target): get {resource}\n") }; @@ -162,6 +165,28 @@ impl ConnectorCommon for Cybersource { connector_transaction_id: None, }) } + transformers::CybersourceErrorResponse::NotAvailableError(response) => { + let error_response = response + .errors + .iter() + .map(|error_info| { + format!( + "{}: {}", + error_info.error_type.clone().unwrap_or("".to_string()), + error_info.message.clone().unwrap_or("".to_string()) + ) + }) + .collect::<Vec<String>>() + .join(" & "); + Ok(types::ErrorResponse { + status_code: res.status_code, + code: consts::NO_ERROR_CODE.to_string(), + message: error_response.clone(), + reason: Some(error_response), + attempt_status: None, + connector_transaction_id: None, + }) + } } } } @@ -261,6 +286,7 @@ impl api::PaymentIncrementalAuthorization for Cybersource {} impl api::MandateSetup for Cybersource {} impl api::ConnectorAccessToken for Cybersource {} impl api::PaymentToken for Cybersource {} +impl api::ConnectorMandateRevoke for Cybersource {} impl ConnectorIntegration< @@ -347,6 +373,92 @@ impl } } +impl + ConnectorIntegration< + api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > for Cybersource +{ + fn get_headers( + &self, + req: &types::MandateRevokeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_http_method(&self) -> services::Method { + services::Method::Delete + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + req: &types::MandateRevokeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}tms/v1/paymentinstruments/{}", + self.base_url(connectors), + connector_utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)? + )) + } + fn build_request( + &self, + req: &types::MandateRevokeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Delete) + .url(&types::MandateRevokeType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::MandateRevokeType::get_headers( + self, req, connectors, + )?) + .build(), + )) + } + fn handle_response( + &self, + data: &types::MandateRevokeRouterData, + res: types::Response, + ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> { + if matches!(res.status_code, 204) { + Ok(types::MandateRevokeRouterData { + response: Ok(types::MandateRevokeResponseData { + mandate_status: common_enums::MandateStatus::Revoked, + }), + ..data.clone() + }) + } else { + // If http_code != 204 || http_code != 4xx, we dont know any other response scenario yet. + let response_value: serde_json::Value = serde_json::from_slice(&res.response) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + let response_string = response_value.to_string(); + + Ok(types::MandateRevokeRouterData { + response: Err(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: response_string.clone(), + reason: Some(response_string), + status_code: res.status_code, + attempt_status: None, + connector_transaction_id: None, + }), + ..data.clone() + }) + } + } + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Cybersource { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index a5a0a7237ef..cf769f1a2fd 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1742,6 +1742,20 @@ pub struct CybersourceStandardErrorResponse { pub details: Option<Vec<Details>>, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceNotAvailableErrorResponse { + pub errors: Vec<CybersourceNotAvailableErrorObject>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceNotAvailableErrorObject { + #[serde(rename = "type")] + pub error_type: Option<String>, + pub message: Option<String>, +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceServerErrorResponse { @@ -1766,8 +1780,10 @@ pub struct CybersourceAuthenticationErrorResponse { #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum CybersourceErrorResponse { - StandardError(CybersourceStandardErrorResponse), AuthenticationError(CybersourceAuthenticationErrorResponse), + //If the request resource is not available/exists in cybersource + NotAvailableError(CybersourceNotAvailableErrorResponse), + StandardError(CybersourceStandardErrorResponse), } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 0dca3ace947..c44f8cd391e 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -335,6 +335,18 @@ impl PaymentsCaptureRequestData for types::PaymentsCaptureData { } } +pub trait RevokeMandateRequestData { + fn get_connector_mandate_id(&self) -> Result<String, Error>; +} + +impl RevokeMandateRequestData for types::MandateRevokeRequestData { + fn get_connector_mandate_id(&self) -> Result<String, Error> { + self.connector_mandate_id + .clone() + .ok_or_else(missing_field_err("connector_mandate_id")) + } +} + pub trait PaymentsSetupMandateRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_email(&self) -> Result<Email, Error>; diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 55de11549a4..aabd846660c 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -1,13 +1,18 @@ +pub mod utils; + use api_models::payments; use common_utils::{ext_traits::Encode, pii}; use diesel_models::enums as storage_enums; -use error_stack::{report, ResultExt}; +use error_stack::{report, IntoReport, ResultExt}; use futures::future; use router_env::{instrument, logger, tracing}; use super::payments::helpers; use crate::{ - core::errors::{self, RouterResponse, StorageErrorExt}, + core::{ + errors::{self, RouterResponse, StorageErrorExt}, + payments::CallConnectorAction, + }, db::StorageInterface, routes::{metrics, AppState}, services, @@ -16,6 +21,7 @@ use crate::{ api::{ customers, mandates::{self, MandateResponseExt}, + ConnectorData, GetToken, }, domain, storage, transformers::ForeignTryFrom, @@ -44,26 +50,121 @@ pub async fn get_mandate( pub async fn revoke_mandate( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateRevokedResponse> { let db = state.store.as_ref(); let mandate = db - .update_mandate_by_merchant_id_mandate_id( - &merchant_account.merchant_id, - &req.mandate_id, - storage::MandateUpdate::StatusUpdate { - mandate_status: storage::enums::MandateStatus::Revoked, - }, - ) + .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &req.mandate_id) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; - Ok(services::ApplicationResponse::Json( - mandates::MandateRevokedResponse { - mandate_id: mandate.mandate_id, - status: mandate.mandate_status, - }, - )) + let mandate_revoke_status = match mandate.mandate_status { + common_enums::MandateStatus::Active + | common_enums::MandateStatus::Inactive + | common_enums::MandateStatus::Pending => { + let profile_id = if let Some(ref payment_id) = mandate.original_payment_id { + let pi = db + .find_payment_intent_by_payment_id_merchant_id( + payment_id, + &merchant_account.merchant_id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + let profile_id = pi.profile_id.clone().ok_or( + errors::ApiErrorResponse::BusinessProfileNotFound { + id: pi + .profile_id + .unwrap_or_else(|| "Profile id is Null".to_string()), + }, + )?; + Ok(profile_id) + } else { + Err(errors::ApiErrorResponse::PaymentNotFound) + }?; + + let merchant_connector_account = helpers::get_merchant_connector_account( + &state, + &merchant_account.merchant_id, + None, + &key_store, + &profile_id, + &mandate.connector, + mandate.merchant_connector_id.as_ref(), + ) + .await?; + + let connector_data = ConnectorData::get_connector_by_name( + &state.conf.connectors, + &mandate.connector, + GetToken::Connector, + mandate.merchant_connector_id.clone(), + )?; + let connector_integration: services::BoxedConnectorIntegration< + '_, + types::api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > = connector_data.connector.get_connector_integration(); + + let router_data = utils::construct_mandate_revoke_router_data( + merchant_connector_account, + &merchant_account, + mandate.clone(), + ) + .await?; + + let response = services::execute_connector_processing_step( + &state, + connector_integration, + &router_data, + CallConnectorAction::Trigger, + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + match response.response { + Ok(_) => { + let update_mandate = db + .update_mandate_by_merchant_id_mandate_id( + &merchant_account.merchant_id, + &req.mandate_id, + storage::MandateUpdate::StatusUpdate { + mandate_status: storage::enums::MandateStatus::Revoked, + }, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + Ok(services::ApplicationResponse::Json( + mandates::MandateRevokedResponse { + mandate_id: update_mandate.mandate_id, + status: update_mandate.mandate_status, + error_code: None, + error_message: None, + }, + )) + } + + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: mandate.connector, + status_code: err.status_code, + reason: err.reason, + }) + .into_report(), + } + } + common_enums::MandateStatus::Revoked => { + Err(errors::ApiErrorResponse::MandateValidationFailed { + reason: "Mandate has already been revoked".to_string(), + }) + .into_report() + } + }; + mandate_revoke_status } #[instrument(skip(db))] diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs new file mode 100644 index 00000000000..25267db1a96 --- /dev/null +++ b/crates/router/src/core/mandate/utils.rs @@ -0,0 +1,76 @@ +use std::marker::PhantomData; + +use common_utils::{errors::CustomResult, ext_traits::ValueExt}; +use diesel_models::Mandate; +use error_stack::ResultExt; + +use crate::{ + core::{errors, payments::helpers}, + types::{self, domain, PaymentAddress}, +}; +const IRRELEVANT_PAYMENT_ID_IN_MANDATE_REVOKE_FLOW: &str = + "irrelevant_payment_id_in_mandate_revoke_flow"; + +const IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW: &str = + "irrelevant_attempt_id_in_mandate_revoke_flow"; + +const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW: &str = + "irrelevant_connector_request_reference_id_in_mandate_revoke_flow"; + +pub async fn construct_mandate_revoke_router_data( + merchant_connector_account: helpers::MerchantConnectorAccountType, + merchant_account: &domain::MerchantAccount, + mandate: Mandate, +) -> CustomResult<types::MandateRevokeRouterData, errors::ApiErrorResponse> { + let auth_type: types::ConnectorAuthType = merchant_connector_account + .get_connector_account_details() + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let router_data = types::RouterData { + flow: PhantomData, + merchant_id: merchant_account.merchant_id.clone(), + customer_id: Some(mandate.customer_id), + connector_customer: None, + connector: mandate.connector, + payment_id: mandate + .original_payment_id + .unwrap_or_else(|| IRRELEVANT_PAYMENT_ID_IN_MANDATE_REVOKE_FLOW.to_string()), + attempt_id: IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW.to_string(), + status: diesel_models::enums::AttemptStatus::default(), + payment_method: diesel_models::enums::PaymentMethod::default(), + connector_auth_type: auth_type, + description: None, + return_url: None, + address: PaymentAddress::default(), + auth_type: diesel_models::enums::AuthenticationType::default(), + connector_meta_data: None, + amount_captured: None, + access_token: None, + session_token: None, + reference_id: None, + payment_method_token: None, + recurring_mandate_payment_data: None, + preprocessing_id: None, + payment_method_balance: None, + connector_api_version: None, + request: types::MandateRevokeRequestData { + mandate_id: mandate.mandate_id, + connector_mandate_id: mandate.connector_mandate_id, + }, + response: Err(types::ErrorResponse::get_not_implemented()), + payment_method_id: None, + connector_request_reference_id: + IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW.to_string(), + test_mode: None, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + frm_metadata: None, + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + }; + + Ok(router_data) +} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index ec8e13cff50..27ddd3f6d81 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -2197,3 +2197,83 @@ default_imp_for_incremental_authorization!( connector::Worldpay, connector::Zen ); + +macro_rules! default_imp_for_revoking_mandates { + ($($path:ident::$connector:ident),*) => { + $( impl api::ConnectorMandateRevoke for $path::$connector {} + impl + services::ConnectorIntegration< + api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::ConnectorMandateRevoke for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > for connector::DummyConnector<T> +{ +} +default_imp_for_revoking_mandates!( + connector::Aci, + connector::Adyen, + connector::Airwallex, + connector::Authorizedotnet, + connector::Bambora, + connector::Bankofamerica, + connector::Bitpay, + connector::Bluesnap, + connector::Boku, + connector::Braintree, + connector::Cashtocode, + connector::Checkout, + connector::Cryptopay, + connector::Coinbase, + connector::Dlocal, + connector::Fiserv, + connector::Forte, + connector::Globalpay, + connector::Globepay, + connector::Gocardless, + connector::Helcim, + connector::Iatapay, + connector::Klarna, + connector::Mollie, + connector::Multisafepay, + connector::Nexinets, + connector::Nmi, + connector::Noon, + connector::Nuvei, + connector::Opayo, + connector::Opennode, + connector::Payeezy, + connector::Payme, + connector::Paypal, + connector::Payu, + connector::Placetopay, + connector::Powertranz, + connector::Prophetpay, + connector::Rapyd, + connector::Riskified, + connector::Signifyd, + connector::Square, + connector::Stax, + connector::Stripe, + connector::Shift4, + connector::Trustpay, + connector::Tsys, + connector::Volt, + connector::Wise, + connector::Worldline, + connector::Worldpay, + connector::Zen +); diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 1e446136297..ecc89a10fa2 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -80,7 +80,9 @@ pub async fn revoke_mandate( state, &req, mandate_id, - |state, auth, req| mandate::revoke_mandate(state, auth.merchant_account, req), + |state, auth, req| { + mandate::revoke_mandate(state, auth.merchant_account, auth.key_store, req) + }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 50aba3de7b5..2225c2965bc 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -19,8 +19,9 @@ use std::{collections::HashMap, marker::PhantomData}; pub use api_models::{ enums::{Connector, PayoutConnectors}, - payouts as payout_types, + mandates, payouts as payout_types, }; +use common_enums::MandateStatus; pub use common_utils::request::{RequestBody, RequestContent}; use common_utils::{pii, pii::Email}; use data_models::mandates::MandateData; @@ -117,6 +118,11 @@ pub type SetupMandateType = dyn services::ConnectorIntegration< SetupMandateRequestData, PaymentsResponseData, >; +pub type MandateRevokeType = dyn services::ConnectorIntegration< + api::MandateRevoke, + MandateRevokeRequestData, + MandateRevokeResponseData, +>; pub type PaymentsPreProcessingType = dyn services::ConnectorIntegration< api::PreProcessing, PaymentsPreProcessingData, @@ -246,6 +252,9 @@ pub type RetrieveFileRouterData = pub type DefendDisputeRouterData = RouterData<api::Defend, DefendDisputeRequestData, DefendDisputeResponse>; +pub type MandateRevokeRouterData = + RouterData<api::MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; + #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; @@ -373,8 +382,8 @@ pub struct PayoutsFulfillResponseData { #[derive(Debug, Clone)] pub struct PaymentsAuthorizeData { pub payment_method_data: payments::PaymentMethodData, - /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) - /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately + /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) + /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately /// ``` /// get_original_amount() /// get_surcharge_amount() @@ -957,6 +966,17 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { pub http_code: u16, } +#[derive(Debug, Clone)] +pub struct MandateRevokeRequestData { + pub mandate_id: String, + pub connector_mandate_id: Option<String>, +} + +#[derive(Debug, Clone)] +pub struct MandateRevokeResponseData { + pub mandate_status: MandateStatus, +} + // Different patterns of authentication. #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index fcbd3801c94..b60153eaf19 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -70,6 +70,18 @@ pub trait ConnectorVerifyWebhookSource: { } +#[derive(Clone, Debug)] +pub struct MandateRevoke; + +pub trait ConnectorMandateRevoke: + ConnectorIntegration< + MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, +> +{ +} + pub trait ConnectorTransactionId: ConnectorCommon + Sync { fn connector_transaction_id( &self, @@ -159,6 +171,7 @@ pub trait Connector: + Payouts + ConnectorVerifyWebhookSource + FraudCheck + + ConnectorMandateRevoke { } @@ -179,7 +192,8 @@ impl< + ConnectorTransactionId + Payouts + ConnectorVerifyWebhookSource - + FraudCheck, + + FraudCheck + + ConnectorMandateRevoke, > Connector for T { } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index bf373220fde..d7942c17447 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -6746,6 +6746,18 @@ }, "status": { "$ref": "#/components/schemas/MandateStatus" + }, + "error_code": { + "type": "string", + "description": "If there was an error while calling the connectors the code is received here", + "example": "E0001", + "nullable": true + }, + "error_message": { + "type": "string", + "description": "If there was an error while calling the connector the error message is received here", + "example": "Failed while verifying the card", + "nullable": true } } },
2024-01-07T21:47:25Z
## 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 Revoke Mandate flow: When the merchant invokes the revoke-mandate endpoint, the mandate should be revoked at both the connector level and core level. ### 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 mandate (zero and non-zero) with the connector - Make Payment using the mandates - Revoke the mandate - Try to revoke an already revoked mandate ### Revoke a Mandate <img width="1119" alt="Screenshot 2024-01-08 at 12 26 34 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/ed66827d-c74c-4b39-9e42-9bae5d15dc31"> ### Try to revoke already revoked mandate <img width="1123" alt="Screenshot 2024-01-08 at 12 26 45 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/c46cc8a6-26cc-49f0-b3b4-78565364a85e"> ### Make Payment with revoked mandate <img width="1100" alt="Screenshot 2024-01-08 at 12 27 18 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/e74ab57a-27f7-46e8-b01d-46af4b164ed7"> ### Handle Error Response from connector <img width="1160" alt="Screenshot 2024-01-08 at 3 28 17 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/9668538d-c83e-4e64-98d6-f8a6a08e91d8"> ### Not implemented Error <img width="1177" alt="Screenshot 2024-01-08 at 5 58 31 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/82de1e70-6b9f-4d73-a4ec-389b44d69239"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3cd74966b279dc1c43935dc1bceb1c69b9eb0643
juspay/hyperswitch
juspay__hyperswitch-3232
Bug: [BUG]: Recurring Payments via Wallets for Cybersource ### Bug Description Recurring/Subsequent Mandate payments are not working for cyber source when the payment_method is wallets ### Expected Behavior Zero and non-zero, recurring and non-recurring payments should flow for cards and wallets via cyber source ### Actual Behavior Recurring/Subsequent Mandate payments are not working for cyber source when the payment_method is wallets ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/development.toml b/config/development.toml index d365abc4674..6e7e040906a 100644 --- a/config/development.toml +++ b/config/development.toml @@ -468,8 +468,8 @@ connectors_with_webhook_source_verification_call = "paypal" [mandates.supported_payment_methods] pay_later.klarna = { connector_list = "adyen" } -wallet.google_pay = { connector_list = "stripe,adyen" } -wallet.apple_pay = { connector_list = "stripe,adyen" } +wallet.google_pay = { connector_list = "stripe,adyen,cybersource" } +wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } wallet.paypal = { connector_list = "adyen" } card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 147e50a9e91..a5a0a7237ef 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -78,7 +78,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { }; let (action_list, action_token_types, authorization_options) = ( Some(vec![CybersourceActionsList::TokenCreate]), - Some(vec![CybersourceActionsTokenType::InstrumentIdentifier]), + Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { initiator: CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), @@ -89,38 +89,122 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { }), ); - let processing_information = ProcessingInformation { - capture: Some(false), - capture_options: None, - action_list, - action_token_types, - authorization_options, - commerce_indicator: CybersourceCommerceIndicator::Internet, - payment_solution: None, - }; - let client_reference_information = ClientReferenceInformation { code: Some(item.connector_request_reference_id.clone()), }; - let payment_information = match item.request.payment_method_data.clone() { + let (payment_information, solution) = match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(ccard) => { - let card = CardDetails::PaymentCard(Card { - number: ccard.card_number, - expiration_month: ccard.card_exp_month, - expiration_year: ccard.card_exp_year, - security_code: ccard.card_cvc, - card_type: None, - }); - PaymentInformation::Cards(CardPaymentInformation { - card, - instrument_identifier: None, - }) + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + ( + PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }), + None, + ) } + + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + payments::WalletData::ApplePay(apple_pay_data) => { + match item.payment_method_token.clone() { + Some(payment_method_token) => match payment_method_token { + types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { + let expiration_month = decrypt_data.get_expiry_month()?; + let expiration_year = decrypt_data.get_four_digit_expiry_year()?; + ( + PaymentInformation::ApplePay(ApplePayPaymentInformation { + tokenized_card: TokenizedCard { + number: decrypt_data.application_primary_account_number, + cryptogram: decrypt_data + .payment_data + .online_payment_cryptogram, + transaction_type: TransactionType::ApplePay, + expiration_year, + expiration_month, + }, + }), + Some(PaymentSolution::ApplePay), + ) + } + types::PaymentMethodToken::Token(_) => { + Err(errors::ConnectorError::InvalidWalletToken)? + } + }, + None => ( + PaymentInformation::ApplePayToken(ApplePayTokenPaymentInformation { + fluid_data: FluidData { + value: Secret::from(apple_pay_data.payment_data), + }, + tokenized_card: ApplePayTokenizedCard { + transaction_type: TransactionType::ApplePay, + }, + }), + Some(PaymentSolution::ApplePay), + ), + } + } + payments::WalletData::GooglePay(google_pay_data) => ( + PaymentInformation::GooglePay(GooglePayPaymentInformation { + fluid_data: FluidData { + value: Secret::from( + consts::BASE64_ENGINE + .encode(google_pay_data.tokenization_data.token), + ), + }, + }), + Some(PaymentSolution::GooglePay), + ), + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayRedirect(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::WeChatPayQr(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ))?, + }, _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ))?, }; + + let processing_information = ProcessingInformation { + capture: Some(false), + capture_options: None, + action_list, + action_token_types, + authorization_options, + commerce_indicator: CybersourceCommerceIndicator::Internet, + payment_solution: solution.map(String::from), + }; Ok(Self { processing_information, payment_information, @@ -169,7 +253,7 @@ pub enum CybersourceActionsList { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum CybersourceActionsTokenType { - InstrumentIdentifier, + PaymentInstrument, } #[derive(Debug, Serialize)] @@ -216,8 +300,7 @@ pub struct CaptureOptions { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardPaymentInformation { - card: CardDetails, - instrument_identifier: Option<CybersoucreInstrumentIdentifier>, + card: Card, } #[derive(Debug, Serialize)] @@ -249,6 +332,12 @@ pub struct ApplePayPaymentInformation { tokenized_card: TokenizedCard, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MandatePaymentInformation { + payment_instrument: Option<CybersoucrePaymentInstrument>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct FluidData { @@ -268,20 +357,13 @@ pub enum PaymentInformation { GooglePay(GooglePayPaymentInformation), ApplePay(ApplePayPaymentInformation), ApplePayToken(ApplePayTokenPaymentInformation), + MandatePayment(MandatePaymentInformation), } #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CybersoucreInstrumentIdentifier { +pub struct CybersoucrePaymentInstrument { id: String, } - -#[derive(Debug, Serialize)] -#[serde(untagged)] -pub enum CardDetails { - PaymentCard(Card), - MandateCard(MandateCardDetails), -} - #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { @@ -292,14 +374,6 @@ pub struct Card { #[serde(rename = "type")] card_type: Option<String>, } - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct MandateCardDetails { - expiration_month: Secret<String>, - expiration_year: Secret<String>, -} - #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationWithBill { @@ -394,7 +468,7 @@ impl if item.router_data.request.setup_future_usage.is_some() { ( Some(vec![CybersourceActionsList::TokenCreate]), - Some(vec![CybersourceActionsTokenType::InstrumentIdentifier]), + Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { initiator: CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), @@ -507,33 +581,16 @@ impl Err(_) => None, }; - let instrument_identifier = - item.router_data - .request - .connector_mandate_id() - .map(|mandate_token_id| CybersoucreInstrumentIdentifier { - id: mandate_token_id, - }); - - let card = if instrument_identifier.is_some() { - CardDetails::MandateCard(MandateCardDetails { - expiration_month: ccard.card_exp_month, - expiration_year: ccard.card_exp_year, - }) - } else { - CardDetails::PaymentCard(Card { + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: ccard.card_cvc, card_type, - }) - }; - - let payment_information = PaymentInformation::Cards(CardPaymentInformation { - card, - instrument_identifier, + }, }); + let processing_information = ProcessingInformation::from((item, None)); let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = @@ -726,13 +783,42 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> ) .into()), }, + payments::PaymentMethodData::MandatePayment => { + let processing_information = ProcessingInformation::from((item, None)); + let payment_instrument = + item.router_data + .request + .connector_mandate_id() + .map(|mandate_token_id| CybersoucrePaymentInstrument { + id: mandate_token_id, + }); + + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + let payment_information = + PaymentInformation::MandatePayment(MandatePaymentInformation { + payment_instrument, + }); + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + }) + } payments::PaymentMethodData::CardRedirect(_) | payments::PaymentMethodData::PayLater(_) | payments::PaymentMethodData::BankRedirect(_) | payments::PaymentMethodData::BankDebit(_) | payments::PaymentMethodData::BankTransfer(_) | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::MandatePayment | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) @@ -1019,14 +1105,11 @@ pub struct CybersourcePaymentsIncrementalAuthorizationResponse { error_information: Option<CybersourceErrorInformation>, } -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CybersourceSetupMandatesResponse { - id: String, - status: CybersourcePaymentStatus, - error_information: Option<CybersourceErrorInformation>, - client_reference_information: Option<ClientReferenceInformation>, - token_information: Option<CybersourceTokenInformation>, +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum CybersourceSetupMandatesResponse { + ClientReferenceInformation(CybersourceClientReferenceResponse), + ErrorInformation(CybersourceErrorInformationResponse), } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1038,7 +1121,7 @@ pub struct ClientReferenceInformation { #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceTokenInformation { - instrument_identifier: CybersoucreInstrumentIdentifier, + payment_instrument: CybersoucrePaymentInstrument, } #[derive(Debug, Clone, Deserialize)] @@ -1161,7 +1244,7 @@ fn get_payment_response( .token_information .clone() .map(|token_info| types::MandateReference { - connector_mandate_id: Some(token_info.instrument_identifier.id), + connector_mandate_id: Some(token_info.payment_instrument.id), payment_method_id: None, }); Ok(types::PaymentsResponseData::TransactionResponse { @@ -1327,51 +1410,66 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let mandate_reference = - item.response - .token_information - .map(|token_info| types::MandateReference { - connector_mandate_id: Some(token_info.instrument_identifier.id), - payment_method_id: None, + match item.response { + CybersourceSetupMandatesResponse::ClientReferenceInformation(info_response) => { + let mandate_reference = info_response.token_information.clone().map(|token_info| { + types::MandateReference { + connector_mandate_id: Some(token_info.payment_instrument.id), + payment_method_id: None, + } }); - let mut mandate_status = enums::AttemptStatus::foreign_from((item.response.status, false)); - if matches!(mandate_status, enums::AttemptStatus::Authorized) { - //In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well. - mandate_status = enums::AttemptStatus::Charged - } - Ok(Self { - status: mandate_status, - response: match item.response.error_information { - Some(error) => Err(types::ErrorResponse { + let mut mandate_status = + enums::AttemptStatus::foreign_from((info_response.status.clone(), false)); + if matches!(mandate_status, enums::AttemptStatus::Authorized) { + //In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well. + mandate_status = enums::AttemptStatus::Charged + } + let error_response = + get_error_response_if_failure((&info_response, mandate_status, item.http_code)); + + Ok(Self { + status: mandate_status, + response: match error_response { + Some(error) => Err(error), + None => Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + info_response.id.clone(), + ), + redirection_data: None, + mandate_reference, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .clone() + .unwrap_or(info_response.id), + ), + incremental_authorization_allowed: Some( + mandate_status == enums::AttemptStatus::Authorized, + ), + }), + }, + ..item.data + }) + } + CybersourceSetupMandatesResponse::ErrorInformation(error_response) => Ok(Self { + response: Err(types::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), - message: error + message: error_response + .error_information .message .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error.reason, + reason: error_response.error_information.reason, status_code: item.http_code, attempt_status: None, - connector_transaction_id: Some(item.response.id), - }), - _ => Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.id.clone(), - ), - redirection_data: None, - mandate_reference, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: item - .response - .client_reference_information - .map(|cref| cref.code) - .unwrap_or(Some(item.response.id)), - incremental_authorization_allowed: Some( - mandate_status == enums::AttemptStatus::Authorized, - ), + connector_transaction_id: Some(error_response.id.clone()), }), - }, - ..item.data - }) + status: enums::AttemptStatus::Failure, + ..item.data + }), + } } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index bfd747640d3..aed22eaedc8 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1770,24 +1770,10 @@ where .unwrap_or(false); let payment_data_and_tokenization_action = match connector { - Some(connector_name) if is_mandate => { - if connector_name == *"cybersource" { - let (_operation, payment_method_data) = operation - .to_domain()? - .make_pm_data( - state, - payment_data, - validate_result.storage_scheme, - merchant_key_store, - ) - .await?; - payment_data.payment_method_data = payment_method_data; - } - ( - payment_data.to_owned(), - TokenizationAction::SkipConnectorTokenization, - ) - } + Some(_) if is_mandate => ( + payment_data.to_owned(), + TokenizationAction::SkipConnectorTokenization, + ), Some(connector) if is_operation_confirm(&operation) => { let payment_method = &payment_data .payment_attempt @@ -1870,7 +1856,7 @@ where }; (payment_data.to_owned(), connector_tokenization_action) } - Some(_) | None => ( + _ => ( payment_data.to_owned(), TokenizationAction::SkipConnectorTokenization, ),
2024-01-02T13:07:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - [fix]: Recurring Payments via Wallets - [feat]: Implement zero dollar mandates and recurring payments via wallets - [refactor]: Update the mandate token created with cybersource from `instrumentIdentifier` to `PaymentInstrument` ### 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 Merchant and an Mca for cyberource - Make a setup mandate payment for card and also for wallet - Make a recurring mandate payment for card and also google_pay - The payment should succeed - Test both zero and non-zero mandate creation <img width="1177" alt="Screenshot 2024-01-03 at 4 50 42 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/fa2db15d-2aea-43fe-a80a-18772facc124"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e06ba148b666772fe79d7050d0c505dd2f04f87c
juspay/hyperswitch
juspay__hyperswitch-3190
Bug: [FEATURE] Replace Routing cache with Moka ### Feature Description Have to replace static routing cache with moka cache in order to use extra features like TTL ### Possible Implementation Just need to replace the current cache. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 4c2ebb516e6..b50c5b69681 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1245,17 +1245,6 @@ pub async fn update_payment_connector( } } - // The purpose of this merchant account update is just to update the - // merchant account `modified_at` field for KGraph cache invalidation - db.update_specific_fields_in_merchant( - merchant_id, - storage::MerchantAccountUpdate::ModifiedAtUpdate, - &key_store, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("error updating the merchant account when updating payment connector")?; - let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: None, connector_type: Some(req.connector_type), diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ff48d181a77..175400c54bf 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3192,7 +3192,6 @@ where connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &TransactionData::Payment(payment_data), eligible_connectors, @@ -3250,7 +3249,6 @@ where connectors = routing::perform_eligibility_analysis_with_fallback( &state, key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &TransactionData::Payment(payment_data), eligible_connectors, @@ -3680,7 +3678,6 @@ where let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &transaction_data, eligible_connectors, diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 802ba524cc6..d45f804268b 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -13,7 +13,6 @@ use api_models::{ payments::Address, routing::ConnectorSelection, }; -use common_utils::static_cache::StaticCache; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ @@ -33,6 +32,7 @@ use rand::{ SeedableRng, }; use rustc_hash::FxHashMap; +use storage_impl::redis::cache::{CGRAPH_CACHE, ROUTING_CACHE}; #[cfg(feature = "payouts")] use crate::core::payouts; @@ -53,7 +53,7 @@ use crate::{ AppState, }; -pub(super) enum CachedAlgorithm { +pub enum CachedAlgorithm { Single(Box<routing_types::RoutableConnectorChoice>), Priority(Vec<routing_types::RoutableConnectorChoice>), VolumeSplit(Vec<routing_types::ConnectorVolumeSplit>), @@ -73,7 +73,6 @@ pub struct SessionFlowRoutingInput<'a> { pub struct SessionRoutingPmTypeInput<'a> { state: &'a AppState, key_store: &'a domain::MerchantKeyStore, - merchant_last_modified: i64, attempt_id: &'a str, routing_algorithm: &'a MerchantAccountRoutingAlgorithm, backend_input: dsl_inputs::BackendInput, @@ -84,10 +83,6 @@ pub struct SessionRoutingPmTypeInput<'a> { ))] profile_id: Option<String>, } -static ROUTING_CACHE: StaticCache<CachedAlgorithm> = StaticCache::new(); -static KGRAPH_CACHE: StaticCache< - hyperswitch_constraint_graph::ConstraintGraph<'_, euclid_dir::DirValue>, -> = StaticCache::new(); type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>; @@ -302,20 +297,15 @@ pub async fn perform_static_routing_v1<F: Clone>( return Ok(fallback_config); }; - let key = ensure_algorithm_cached_v1( + let cached_algorithm = ensure_algorithm_cached_v1( state, merchant_id, - algorithm_ref.timestamp, &algorithm_id, #[cfg(feature = "business_profile_routing")] Some(profile_id).cloned(), &api_enums::TransactionType::from(transaction_data), ) .await?; - let cached_algorithm: Arc<CachedAlgorithm> = ROUTING_CACHE - .retrieve(&key) - .change_context(errors::RoutingError::CacheMiss) - .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?; Ok(match cached_algorithm.as_ref() { CachedAlgorithm::Single(conn) => vec![(**conn).clone()], @@ -342,11 +332,10 @@ pub async fn perform_static_routing_v1<F: Clone>( async fn ensure_algorithm_cached_v1( state: &AppState, merchant_id: &str, - timestamp: i64, algorithm_id: &str, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<String> { +) -> RoutingResult<Arc<CachedAlgorithm>> { #[cfg(feature = "business_profile_routing")] let key = { let profile_id = profile_id @@ -376,29 +365,24 @@ async fn ensure_algorithm_cached_v1( } }; - let present = ROUTING_CACHE - .present(&key) - .change_context(errors::RoutingError::DslCachePoisoned) - .attach_printable("Error checking presence of DSL")?; + let cached_algorithm = ROUTING_CACHE + .get_val::<Arc<CachedAlgorithm>>(key.as_str()) + .await; - let expired = ROUTING_CACHE - .expired(&key, timestamp) - .change_context(errors::RoutingError::DslCachePoisoned) - .attach_printable("Error checking expiry of DSL in cache")?; - - if !present || expired { + let algorithm = if let Some(algo) = cached_algorithm { + algo + } else { refresh_routing_cache_v1( state, key.clone(), algorithm_id, - timestamp, #[cfg(feature = "business_profile_routing")] profile_id, ) - .await?; + .await? }; - Ok(key) + Ok(algorithm) } pub fn perform_straight_through_routing( @@ -447,9 +431,8 @@ pub async fn refresh_routing_cache_v1( state: &AppState, key: String, algorithm_id: &str, - timestamp: i64, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, -) -> RoutingResult<()> { +) -> RoutingResult<Arc<CachedAlgorithm>> { #[cfg(feature = "business_profile_routing")] let algorithm = { let algorithm = state @@ -498,12 +481,11 @@ pub async fn refresh_routing_cache_v1( } }; - ROUTING_CACHE - .save(key, cached_algorithm, timestamp) - .change_context(errors::RoutingError::DslCachePoisoned) - .attach_printable("Error saving DSL to cache")?; + let arc_cached_algorithm = Arc::new(cached_algorithm); + + ROUTING_CACHE.push(key, arc_cached_algorithm.clone()).await; - Ok(()) + Ok(arc_cached_algorithm) } pub fn perform_volume_split( @@ -540,10 +522,9 @@ pub fn perform_volume_split( Ok(splits.into_iter().map(|sp| sp.connector).collect()) } -pub async fn get_merchant_kgraph<'a>( +pub async fn get_merchant_cgraph<'a>( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<'a, euclid_dir::DirValue>>> { @@ -556,10 +537,10 @@ pub async fn get_merchant_kgraph<'a>( .get_required_value("profile_id") .change_context(errors::RoutingError::ProfileIdMissing)?; match transaction_type { - api_enums::TransactionType::Payment => format!("kgraph_{}_{}", merchant_id, profile_id), + api_enums::TransactionType::Payment => format!("cgraph_{}_{}", merchant_id, profile_id), #[cfg(feature = "payouts")] api_enums::TransactionType::Payout => { - format!("kgraph_po_{}_{}", merchant_id, profile_id) + format!("cgraph_po_{}_{}", merchant_id, profile_id) } } }; @@ -571,45 +552,36 @@ pub async fn get_merchant_kgraph<'a>( api_enums::TransactionType::Payout => format!("kgraph_po_{}", merchant_id), }; - let kgraph_present = KGRAPH_CACHE - .present(&key) - .change_context(errors::RoutingError::KgraphCacheFailure) - .attach_printable("when checking kgraph presence")?; - - let kgraph_expired = KGRAPH_CACHE - .expired(&key, merchant_last_modified) - .change_context(errors::RoutingError::KgraphCacheFailure) - .attach_printable("when checking kgraph expiry")?; + let cached_cgraph = CGRAPH_CACHE + .get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<'_, euclid_dir::DirValue>>>( + key.as_str(), + ) + .await; - if !kgraph_present || kgraph_expired { - refresh_kgraph_cache( + let cgraph = if let Some(graph) = cached_cgraph { + graph + } else { + refresh_cgraph_cache( state, key_store, - merchant_last_modified, key.clone(), #[cfg(feature = "business_profile_routing")] profile_id, transaction_type, ) - .await?; - } - - let cached_kgraph = KGRAPH_CACHE - .retrieve(&key) - .change_context(errors::RoutingError::CacheMiss) - .attach_printable("when retrieving kgraph")?; + .await? + }; - Ok(cached_kgraph) + Ok(cgraph) } -pub async fn refresh_kgraph_cache( +pub async fn refresh_cgraph_cache<'a>( state: &AppState, key_store: &domain::MerchantKeyStore, - timestamp: i64, key: String, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<()> { +) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<'a, euclid_dir::DirValue>>> { let mut merchant_connector_accounts = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( @@ -672,23 +644,21 @@ pub async fn refresh_kgraph_cache( connector_configs, default_configs, }; - let kgraph = mca_graph::make_mca_graph(api_mcas, &config_pm_filters) - .change_context(errors::RoutingError::KgraphCacheRefreshFailed) - .attach_printable("when construction kgraph")?; + let cgraph = Arc::new( + mca_graph::make_mca_graph(api_mcas, &config_pm_filters) + .change_context(errors::RoutingError::KgraphCacheRefreshFailed) + .attach_printable("when construction cgraph")?, + ); - KGRAPH_CACHE - .save(key, kgraph, timestamp) - .change_context(errors::RoutingError::KgraphCacheRefreshFailed) - .attach_printable("when saving kgraph to cache")?; + CGRAPH_CACHE.push(key, Arc::clone(&cgraph)).await; - Ok(()) + Ok(cgraph) } #[allow(clippy::too_many_arguments)] -async fn perform_kgraph_filtering( +async fn perform_cgraph_filtering( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, chosen: Vec<routing_types::RoutableConnectorChoice>, backend_input: dsl_inputs::BackendInput, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, @@ -700,10 +670,9 @@ async fn perform_kgraph_filtering( .into_context() .change_context(errors::RoutingError::KgraphAnalysisError)?, ); - let cached_kgraph = get_merchant_kgraph( + let cached_cgraph = get_merchant_cgraph( state, key_store, - merchant_last_modified, #[cfg(feature = "business_profile_routing")] profile_id, transaction_type, @@ -717,7 +686,7 @@ async fn perform_kgraph_filtering( let dir_val = euclid_choice .into_dir_value() .change_context(errors::RoutingError::KgraphAnalysisError)?; - let kgraph_eligible = cached_kgraph + let cgraph_eligible = cached_cgraph .check_value_validity( dir_val, &context, @@ -730,7 +699,7 @@ async fn perform_kgraph_filtering( let filter_eligible = eligible_connectors.map_or(true, |list| list.contains(&routable_connector)); - if kgraph_eligible && filter_eligible { + if cgraph_eligible && filter_eligible { final_selection.push(choice); } } @@ -741,7 +710,6 @@ async fn perform_kgraph_filtering( pub async fn perform_eligibility_analysis<F: Clone>( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, chosen: Vec<routing_types::RoutableConnectorChoice>, transaction_data: &routing::TransactionData<'_, F>, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, @@ -753,10 +721,9 @@ pub async fn perform_eligibility_analysis<F: Clone>( routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, }; - perform_kgraph_filtering( + perform_cgraph_filtering( state, key_store, - merchant_last_modified, chosen, backend_input, eligible_connectors, @@ -770,7 +737,6 @@ pub async fn perform_eligibility_analysis<F: Clone>( pub async fn perform_fallback_routing<F: Clone>( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, transaction_data: &routing::TransactionData<'_, F>, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, @@ -801,10 +767,9 @@ pub async fn perform_fallback_routing<F: Clone>( routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, }; - perform_kgraph_filtering( + perform_cgraph_filtering( state, key_store, - merchant_last_modified, fallback_config, backend_input, eligible_connectors, @@ -818,7 +783,6 @@ pub async fn perform_fallback_routing<F: Clone>( pub async fn perform_eligibility_analysis_with_fallback<F: Clone>( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, chosen: Vec<routing_types::RoutableConnectorChoice>, transaction_data: &routing::TransactionData<'_, F>, eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>, @@ -827,7 +791,6 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>( let mut final_selection = perform_eligibility_analysis( state, key_store, - merchant_last_modified, chosen, transaction_data, eligible_connectors.as_ref(), @@ -839,7 +802,6 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>( let fallback_selection = perform_fallback_routing( state, key_store, - merchant_last_modified, transaction_data, eligible_connectors.as_ref(), #[cfg(feature = "business_profile_routing")] @@ -873,11 +835,6 @@ pub async fn perform_session_flow_routing( ) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice>> { let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> = FxHashMap::default(); - let merchant_last_modified = session_input - .merchant_account - .modified_at - .assume_utc() - .unix_timestamp(); #[cfg(feature = "business_profile_routing")] let routing_algorithm: MerchantAccountRoutingAlgorithm = { @@ -995,7 +952,6 @@ pub async fn perform_session_flow_routing( let session_pm_input = SessionRoutingPmTypeInput { state: session_input.state, key_store: session_input.key_store, - merchant_last_modified, attempt_id: &session_input.payment_attempt.attempt_id, routing_algorithm: &routing_algorithm, backend_input: backend_input.clone(), @@ -1035,10 +991,9 @@ async fn perform_session_routing_for_pm_type( let chosen_connectors = match session_pm_input.routing_algorithm { MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => { if let Some(ref algorithm_id) = algorithm_ref.algorithm_id { - let key = ensure_algorithm_cached_v1( + let cached_algorithm = ensure_algorithm_cached_v1( &session_pm_input.state.clone(), merchant_id, - algorithm_ref.timestamp, algorithm_id, #[cfg(feature = "business_profile_routing")] session_pm_input.profile_id.clone(), @@ -1046,11 +1001,6 @@ async fn perform_session_routing_for_pm_type( ) .await?; - let cached_algorithm = ROUTING_CACHE - .retrieve(&key) - .change_context(errors::RoutingError::CacheMiss) - .attach_printable("unable to retrieve cached routing algorithm")?; - match cached_algorithm.as_ref() { CachedAlgorithm::Single(conn) => vec![(**conn).clone()], CachedAlgorithm::Priority(plist) => plist.clone(), @@ -1084,10 +1034,9 @@ async fn perform_session_routing_for_pm_type( } }; - let mut final_selection = perform_kgraph_filtering( + let mut final_selection = perform_cgraph_filtering( &session_pm_input.state.clone(), session_pm_input.key_store, - session_pm_input.merchant_last_modified, chosen_connectors, session_pm_input.backend_input.clone(), None, @@ -1115,10 +1064,9 @@ async fn perform_session_routing_for_pm_type( .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; - final_selection = perform_kgraph_filtering( + final_selection = perform_cgraph_filtering( &session_pm_input.state.clone(), session_pm_input.key_store, - session_pm_input.merchant_last_modified, fallback, session_pm_input.backend_input, None, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 46c3c8c9aab..dad0739879f 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -669,7 +669,6 @@ pub async fn decide_payout_connector( connectors = routing::perform_eligibility_analysis_with_fallback( state, key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &TransactionData::<()>::Payout(payout_data), eligible_connectors, @@ -728,7 +727,6 @@ pub async fn decide_payout_connector( connectors = routing::perform_eligibility_analysis_with_fallback( state, key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &TransactionData::<()>::Payout(payout_data), eligible_connectors, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 894e09ab60e..1d46e54bccf 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -10,10 +10,11 @@ use diesel_models::{ }; use error_stack::ResultExt; use rustc_hash::FxHashSet; +use storage_impl::redis::cache as redis_cache; use crate::{ core::errors::{self, RouterResult}, - db::StorageInterface, + db::{cache, StorageInterface}, types::{domain, storage}, utils::StringExt, }; @@ -239,6 +240,17 @@ pub async fn update_business_profile_active_algorithm_ref( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert routing ref to value")?; + let merchant_id = current_business_profile.merchant_id.clone(); + + #[cfg(feature = "business_profile_routing")] + let profile_id = current_business_profile.profile_id.clone(); + #[cfg(feature = "business_profile_routing")] + let routing_cache_key = redis_cache::CacheKind::Routing( + format!("routing_config_{merchant_id}_{profile_id}").into(), + ); + + #[cfg(not(feature = "business_profile_routing"))] + let routing_cache_key = redis_cache::CacheKind::Routing(format!("dsl_{merchant_id}").into()); let (routing_algorithm, payout_routing_algorithm) = match transaction_type { storage::enums::TransactionType::Payment => (Some(ref_val), None), #[cfg(feature = "payouts")] @@ -272,6 +284,11 @@ pub async fn update_business_profile_active_algorithm_ref( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref in business profile")?; + + cache::publish_into_redact_channel(db, [routing_cache_key]) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate routing cache")?; Ok(()) } diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index c323ca4abb1..0cecb5e8d76 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -513,11 +513,29 @@ async fn publish_and_redact_merchant_account_cache( .as_ref() .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); + #[cfg(feature = "business_profile_routing")] + let kgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { + CacheKind::CGraph( + format!( + "kgraph_{}_{}", + merchant_account.merchant_id.clone(), + profile_id, + ) + .into(), + ) + }); + + #[cfg(not(feature = "business_profile_routing"))] + let kgraph_key = Some(CacheKind::CGraph( + format!("kgraph_{}", merchant_account.merchant_id.clone()).into(), + )); + let mut cache_keys = vec![CacheKind::Accounts( merchant_account.merchant_id.as_str().into(), )]; cache_keys.extend(publishable_key.into_iter()); + cache_keys.extend(kgraph_key.into_iter()); super::cache::publish_into_redact_channel(store, cache_keys).await?; Ok(()) diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 8f50f5f5426..31d965c8cd6 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -427,6 +427,9 @@ impl MerchantConnectorAccountInterface for Store { cache::CacheKind::Accounts( format!("{}_{}", _merchant_id, _merchant_connector_id).into(), ), + cache::CacheKind::CGraph( + format!("cgraph_{}_{_profile_id}", _merchant_id).into(), + ), ], update_call, ) @@ -475,9 +478,16 @@ impl MerchantConnectorAccountInterface for Store { "profile_id".to_string(), ))?; - super::cache::publish_and_redact( + super::cache::publish_and_redact_multiple( self, - cache::CacheKind::Accounts(format!("{}_{}", mca.merchant_id, _profile_id).into()), + [ + cache::CacheKind::Accounts( + format!("{}_{}", mca.merchant_id, _profile_id).into(), + ), + cache::CacheKind::CGraph( + format!("cgraph_{}_{_profile_id}", mca.merchant_id).into(), + ), + ], delete_call, ) .await diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 4cd2fc0c504..80a6847e376 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -21,6 +21,12 @@ const CONFIG_CACHE_PREFIX: &str = "config"; /// Prefix for accounts cache key const ACCOUNTS_CACHE_PREFIX: &str = "accounts"; +/// Prefix for routing cache key +const ROUTING_CACHE_PREFIX: &str = "routing"; + +/// Prefix for kgraph cache key +const CGRAPH_CACHE_PREFIX: &str = "cgraph"; + /// Prefix for all kinds of cache key const ALL_CACHE_PREFIX: &str = "all_cache_kind"; @@ -40,6 +46,14 @@ pub static CONFIG_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_ pub static ACCOUNTS_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); +/// Routing Cache +pub static ROUTING_CACHE: Lazy<Cache> = + Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); + +/// CGraph Cache +pub static CGRAPH_CACHE: Lazy<Cache> = + Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); + /// Trait which defines the behaviour of types that's gonna be stored in Cache pub trait Cacheable: Any + Send + Sync + DynClone { fn as_any(&self) -> &dyn Any; @@ -48,6 +62,8 @@ pub trait Cacheable: Any + Send + Sync + DynClone { pub enum CacheKind<'a> { Config(Cow<'a, str>), Accounts(Cow<'a, str>), + Routing(Cow<'a, str>), + CGraph(Cow<'a, str>), All(Cow<'a, str>), } @@ -56,6 +72,8 @@ impl<'a> From<CacheKind<'a>> for RedisValue { let value = match kind { CacheKind::Config(s) => format!("{CONFIG_CACHE_PREFIX},{s}"), CacheKind::Accounts(s) => format!("{ACCOUNTS_CACHE_PREFIX},{s}"), + CacheKind::Routing(s) => format!("{ROUTING_CACHE_PREFIX},{s}"), + CacheKind::CGraph(s) => format!("{CGRAPH_CACHE_PREFIX},{s}"), CacheKind::All(s) => format!("{ALL_CACHE_PREFIX},{s}"), }; Self::from_string(value) @@ -73,6 +91,8 @@ impl<'a> TryFrom<RedisValue> for CacheKind<'a> { match split.0 { ACCOUNTS_CACHE_PREFIX => Ok(Self::Accounts(Cow::Owned(split.1.to_string()))), CONFIG_CACHE_PREFIX => Ok(Self::Config(Cow::Owned(split.1.to_string()))), + ROUTING_CACHE_PREFIX => Ok(Self::Routing(Cow::Owned(split.1.to_string()))), + CGRAPH_CACHE_PREFIX => Ok(Self::CGraph(Cow::Owned(split.1.to_string()))), ALL_CACHE_PREFIX => Ok(Self::All(Cow::Owned(split.1.to_string()))), _ => Err(validation_err.into()), } @@ -123,6 +143,11 @@ impl Cache { (*val).as_any().downcast_ref::<T>().cloned() } + /// Check if a key exists in cache + pub async fn exists(&self, key: &str) -> bool { + self.inner.contains_key(key) + } + pub async fn remove(&self, key: &str) { self.inner.invalidate(key).await; } diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs index 2922dbcadba..9669e826663 100644 --- a/crates/storage_impl/src/redis/pub_sub.rs +++ b/crates/storage_impl/src/redis/pub_sub.rs @@ -2,7 +2,7 @@ use error_stack::ResultExt; use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue}; use router_env::logger; -use crate::redis::cache::{CacheKind, ACCOUNTS_CACHE, CONFIG_CACHE}; +use crate::redis::cache::{CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, ROUTING_CACHE}; #[async_trait::async_trait] pub trait PubSubInterface { @@ -67,9 +67,19 @@ impl PubSubInterface for redis_interface::RedisConnectionPool { ACCOUNTS_CACHE.remove(key.as_ref()).await; key } + CacheKind::CGraph(key) => { + CGRAPH_CACHE.remove(key.as_ref()).await; + key + } + CacheKind::Routing(key) => { + ROUTING_CACHE.remove(key.as_ref()).await; + key + } CacheKind::All(key) => { CONFIG_CACHE.remove(key.as_ref()).await; ACCOUNTS_CACHE.remove(key.as_ref()).await; + CGRAPH_CACHE.remove(key.as_ref()).await; + ROUTING_CACHE.remove(key.as_ref()).await; key } };
2023-12-28T12:48:19Z
## 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 --> Enabled Moka cache for routing with cache invalidation ### 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)? --> Look for the pub-sub cache invalidation log ![image](https://github.com/juspay/hyperswitch/assets/76486416/e739ac71-2b2b-4103-9804-b4478c5d0e87) ![image](https://github.com/juspay/hyperswitch/assets/76486416/068743c0-a9d0-49af-859d-f23ab32eb2ec) 1. Update an existing Merchant connector account and look for Cgrpah cache invalidation log ``` curl --location --request POST 'http://localhost:8080/account/sarthak/connectors/mca_VaZpO5COiFDUIiMq7DFV' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "metadata": { "city": "NY", "unit": "248" } }' ``` 2. Activate a routing config from dashboard, then search for routing cache invalidation using routing config key ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1523311c479f2caa564b853e668fd47579c2b21f
juspay/hyperswitch
juspay__hyperswitch-3154
Bug: [FEATURE]: [VOLT] Add Support for Webhooks ### Feature Description Adding Support for Payment Webhooks for Volt Connector ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/volt.rs b/crates/router/src/connector/volt.rs index bf36a7bff61..3641c0c3ddc 100644 --- a/crates/router/src/connector/volt.rs +++ b/crates/router/src/connector/volt.rs @@ -2,11 +2,13 @@ pub mod transformers; use std::fmt::Debug; -use common_utils::request::RequestContent; +use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, PeekInterface}; use transformers as volt; +use self::transformers::webhook_headers; +use super::utils; use crate::{ configs::settings, core::errors::{self, CustomResult}, @@ -398,7 +400,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe data: &types::PaymentsSyncRouterData, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - let response: volt::VoltPsyncResponse = res + let response: volt::VoltPaymentsResponseData = res .response .parse_struct("volt PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -586,24 +588,93 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse #[async_trait::async_trait] impl api::IncomingWebhook for Volt { - fn get_webhook_object_reference_id( + fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::HmacSha256)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let signature = + utils::get_header_key_value(webhook_headers::X_VOLT_SIGNED, request.headers) + .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; + + hex::decode(signature) + .into_report() + .change_context(errors::ConnectorError::WebhookVerificationSecretInvalid) + } + + fn get_webhook_source_verification_message( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + _merchant_id: &str, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let x_volt_timed = + utils::get_header_key_value(webhook_headers::X_VOLT_TIMED, request.headers)?; + let user_agent = utils::get_header_key_value(webhook_headers::USER_AGENT, request.headers)?; + let version = user_agent + .split('/') + .last() + .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; + Ok(format!( + "{}|{}|{}", + String::from_utf8_lossy(request.body), + x_volt_timed, + version + ) + .into_bytes()) + } + + fn get_webhook_object_reference_id( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let webhook_body: volt::VoltWebhookBodyReference = request + .body + .parse_struct("VoltWebhookBodyReference") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + let reference = match webhook_body.merchant_internal_reference { + Some(merchant_internal_reference) => { + api_models::payments::PaymentIdType::PaymentAttemptId(merchant_internal_reference) + } + None => { + api_models::payments::PaymentIdType::ConnectorTransactionId(webhook_body.payment) + } + }; + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + reference, + )) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + if request.body.is_empty() { + Ok(api::IncomingWebhookEvent::EndpointVerification) + } else { + let payload: volt::VoltWebhookBodyEventType = request + .body + .parse_struct("VoltWebhookBodyEventType") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + Ok(api::IncomingWebhookEvent::from(payload.status)) + } } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let details: volt::VoltWebhookObjectResource = request + .body + .parse_struct("VoltWebhookObjectResource") + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + Ok(Box::new(details)) } } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index 9ee2a3f012e..4c6eaeb52f4 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{self, AddressDetailsData, RouterData}, + consts, core::errors, services, types::{self, api, storage::enums as storage_enums}, @@ -41,6 +42,12 @@ impl<T> } } +pub mod webhook_headers { + pub const X_VOLT_SIGNED: &str = "X-Volt-Signed"; + pub const X_VOLT_TIMED: &str = "X-Volt-Timed"; + pub const USER_AGENT: &str = "User-Agent"; +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltPaymentsRequest { @@ -50,7 +57,6 @@ pub struct VoltPaymentsRequest { transaction_type: TransactionType, merchant_internal_reference: String, shopper: ShopperDetails, - notification_url: Option<String>, payment_success_url: Option<String>, payment_failure_url: Option<String>, payment_pending_url: Option<String>, @@ -91,7 +97,6 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme let payment_failure_url = item.router_data.request.router_return_url.clone(); let payment_pending_url = item.router_data.request.router_return_url.clone(); let payment_cancel_url = item.router_data.request.router_return_url.clone(); - let notification_url = item.router_data.request.webhook_url.clone(); let address = item.router_data.get_billing_address()?; let shopper = ShopperDetails { email: item.router_data.request.email.clone(), @@ -109,7 +114,6 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme payment_failure_url, payment_pending_url, payment_cancel_url, - notification_url, shopper, transaction_type, }) @@ -291,8 +295,9 @@ impl<F, T> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[derive(strum::Display)] pub enum VoltPaymentStatus { NewPayment, Completed, @@ -309,7 +314,15 @@ pub enum VoltPaymentStatus { Failed, Settled, } -#[derive(Debug, Deserialize)] + +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum VoltPaymentsResponseData { + WebhookResponse(VoltWebhookObjectResource), + PsyncResponse(VoltPsyncResponse), +} + +#[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VoltPsyncResponse { status: VoltPaymentStatus, @@ -317,29 +330,102 @@ pub struct VoltPsyncResponse { merchant_internal_reference: Option<String>, } -impl<F, T> TryFrom<types::ResponseRouterData<F, VoltPsyncResponse, T, types::PaymentsResponseData>> +impl<F, T> + TryFrom<types::ResponseRouterData<F, VoltPaymentsResponseData, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, VoltPsyncResponse, T, types::PaymentsResponseData>, + item: types::ResponseRouterData< + F, + VoltPaymentsResponseData, + T, + types::PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { - Ok(Self { - status: enums::AttemptStatus::from(item.response.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: item - .response - .merchant_internal_reference - .or(Some(item.response.id)), - incremental_authorization_allowed: None, - }), - ..item.data - }) + match item.response { + VoltPaymentsResponseData::PsyncResponse(payment_response) => { + let status = enums::AttemptStatus::from(payment_response.status.clone()); + Ok(Self { + status, + response: if is_payment_failure(status) { + Err(types::ErrorResponse { + code: payment_response.status.clone().to_string(), + message: payment_response.status.clone().to_string(), + reason: Some(payment_response.status.to_string()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(payment_response.id), + }) + } else { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + payment_response.id.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: payment_response + .merchant_internal_reference + .or(Some(payment_response.id)), + incremental_authorization_allowed: None, + }) + }, + ..item.data + }) + } + VoltPaymentsResponseData::WebhookResponse(webhook_response) => { + let detailed_status = webhook_response.detailed_status.clone(); + let status = enums::AttemptStatus::from(webhook_response.status); + Ok(Self { + status, + response: if is_payment_failure(status) { + Err(types::ErrorResponse { + code: detailed_status + .clone() + .map(|volt_status| volt_status.to_string()) + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned()), + message: detailed_status + .clone() + .map(|volt_status| volt_status.to_string()) + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()), + reason: detailed_status + .clone() + .map(|volt_status| volt_status.to_string()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(webhook_response.payment.clone()), + }) + } else { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + webhook_response.payment.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: webhook_response + .merchant_internal_reference + .or(Some(webhook_response.payment)), + incremental_authorization_allowed: None, + }) + }, + ..item.data + }) + } + } + } +} + +impl From<VoltWebhookStatus> for enums::AttemptStatus { + fn from(status: VoltWebhookStatus) -> Self { + match status { + VoltWebhookStatus::Completed | VoltWebhookStatus::Received => Self::Charged, + VoltWebhookStatus::Failed | VoltWebhookStatus::NotReceived => Self::Failure, + VoltWebhookStatus::Pending => Self::Pending, + } } } @@ -405,6 +491,68 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } +#[derive(Debug, Deserialize, Clone, Serialize)] +pub struct VoltWebhookBodyReference { + pub payment: String, + pub merchant_internal_reference: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct VoltWebhookBodyEventType { + pub status: VoltWebhookStatus, + pub detailed_status: Option<VoltDetailedStatus>, +} + +#[derive(Debug, Deserialize, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct VoltWebhookObjectResource { + pub payment: String, + pub merchant_internal_reference: Option<String>, + pub status: VoltWebhookStatus, + pub detailed_status: Option<VoltDetailedStatus>, +} + +#[derive(Debug, Deserialize, Clone, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum VoltWebhookStatus { + Completed, + Failed, + Pending, + Received, + NotReceived, +} + +#[derive(Debug, Deserialize, Clone, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[derive(strum::Display)] +pub enum VoltDetailedStatus { + RefusedByRisk, + RefusedByBank, + ErrorAtBank, + CancelledByUser, + AbandonedByUser, + Failed, + Completed, + BankRedirect, + DelayedAtBank, + AwaitingCheckoutAuthorisation, +} + +impl From<VoltWebhookStatus> for api::IncomingWebhookEvent { + fn from(status: VoltWebhookStatus) -> Self { + match status { + VoltWebhookStatus::Completed | VoltWebhookStatus::Received => { + Self::PaymentIntentSuccess + } + VoltWebhookStatus::Failed | VoltWebhookStatus::NotReceived => { + Self::PaymentIntentFailure + } + VoltWebhookStatus::Pending => Self::PaymentIntentProcessing, + } + } +} + #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct VoltErrorResponse { pub exception: VoltErrorException, @@ -429,3 +577,32 @@ pub struct VoltErrorList { pub property: String, pub message: String, } + +fn is_payment_failure(status: enums::AttemptStatus) -> bool { + match status { + common_enums::AttemptStatus::AuthenticationFailed + | common_enums::AttemptStatus::AuthorizationFailed + | common_enums::AttemptStatus::CaptureFailed + | common_enums::AttemptStatus::VoidFailed + | common_enums::AttemptStatus::Failure => true, + common_enums::AttemptStatus::Started + | common_enums::AttemptStatus::RouterDeclined + | common_enums::AttemptStatus::AuthenticationPending + | common_enums::AttemptStatus::AuthenticationSuccessful + | common_enums::AttemptStatus::Authorized + | common_enums::AttemptStatus::Charged + | common_enums::AttemptStatus::Authorizing + | common_enums::AttemptStatus::CodInitiated + | common_enums::AttemptStatus::Voided + | common_enums::AttemptStatus::VoidInitiated + | common_enums::AttemptStatus::CaptureInitiated + | common_enums::AttemptStatus::AutoRefunded + | common_enums::AttemptStatus::PartialCharged + | common_enums::AttemptStatus::PartialChargedAndChargeable + | common_enums::AttemptStatus::Unresolved + | common_enums::AttemptStatus::Pending + | common_enums::AttemptStatus::PaymentMethodAwaited + | common_enums::AttemptStatus::ConfirmationAwaited + | common_enums::AttemptStatus::DeviceDataCollectionPending => false, + } +}
2023-12-17T18:47:23Z
## Type of Change Support for Webhooks for Volt Connector - [ ] Bugfix - [ ] New feature - [ ] 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). --> ## How did you test it? ![Screenshot 2024-01-03 at 8 28 35 PM 2](https://github.com/juspay/hyperswitch/assets/85639103/e2a0a038-6b92-4319-a94b-a57d976b205b) ```json { "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "bank_redirect", "payment_method_type": "open_banking_uk", "payment_method_data": { "bank_redirect": { "open_banking_uk": { } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "business_label": "food", "business_country": "US" } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
252443a50dc48939eb08b3bcd67273bb71bbe349
juspay/hyperswitch
juspay__hyperswitch-3251
Bug: Rename `kms` feature flag to `aws_kms` Rename `kms` feature flag to `aws_kms`, `kms` files to `aws_kms` and the components of kms to include `aws` as its prefix. This change is required so that current kms encryption becomes distinguishable, especially if in future new encryption implementations like a AWS KMS alternative is integrated.
diff --git a/README.md b/README.md index 0f5e924589f..0da065eeba6 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ should be introduced, checking it agrees with the actual structure --> │ ├── data_models : Represents the data/domain models used by the business/domain layer │ ├── diesel_models : Database models shared across `router` and other crates │ ├── drainer : Application that reads Redis streams and executes queries in database -│ ├── external_services : Interactions with external systems like emails, KMS, etc. +│ ├── external_services : Interactions with external systems like emails, AWS KMS, etc. │ ├── masking : Personal Identifiable Information protection │ ├── redis_interface : A user-friendly interface to Redis │ ├── router : Main crate of the project diff --git a/config/config.example.toml b/config/config.example.toml index 87999f0e9e9..027adee5f68 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -322,7 +322,7 @@ paypal = { currency = "USD,INR", country = "US" } # ^------------------------------- any valid payment method type (can be multiple) (for cards this should be card_network) # If either currency or country isn't provided then, all possible values are accepted -# KMS configuration. Only applicable when the `kms` feature flag is enabled. +# AWS KMS configuration. Only applicable when the `aws_kms` feature flag is enabled. [kms] key_id = "" # The AWS key ID used by the KMS SDK for decrypting data. region = "" # The AWS region used by the KMS SDK for decrypting data. diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 67169a15104..adffb39875d 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -8,8 +8,8 @@ readme = "README.md" license.workspace = true [features] -release = ["kms", "vergen"] -kms = ["external_services/kms"] +release = ["aws_kms", "vergen"] +aws_kms = ["external_services/aws_kms"] hashicorp-vault = ["external_services/hashicorp-vault"] vergen = ["router_env/vergen"] diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs index 6af0a978223..788ff1456e2 100644 --- a/crates/drainer/src/connection.rs +++ b/crates/drainer/src/connection.rs @@ -1,10 +1,10 @@ use bb8::PooledConnection; use diesel::PgConnection; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::{self, decrypt::VaultFetch, Kv2}; -#[cfg(feature = "kms")] -use external_services::kms::{self, decrypt::KmsDecrypt}; -#[cfg(not(feature = "kms"))] +#[cfg(not(feature = "aws_kms"))] use masking::PeekInterface; use crate::settings::Database; @@ -28,7 +28,7 @@ pub async fn redis_connection( pub async fn diesel_make_pg_pool( database: &Database, _test_transaction: bool, - #[cfg(feature = "kms")] kms_client: &'static kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static hashicorp_vault::HashiCorpVault, ) -> PgPool { let password = database.password.clone(); @@ -38,13 +38,13 @@ pub async fn diesel_make_pg_pool( .await .expect("Failed while fetching db password"); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let password = password - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .expect("Failed to decrypt password"); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let password = &password.peek(); let database_url = format!( diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 4393ebb9dc9..77ee980e901 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -27,8 +27,8 @@ impl Store { master_pool: diesel_make_pg_pool( &config.master_database, test_transaction, - #[cfg(feature = "kms")] - external_services::kms::get_kms_client(&config.kms).await, + #[cfg(feature = "aws_kms")] + external_services::aws_kms::get_aws_kms_client(&config.kms).await, #[cfg(feature = "hashicorp-vault")] #[allow(clippy::expect_used)] external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 5b80ee375f5..a60612f8b24 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -2,10 +2,10 @@ use std::path::PathBuf; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; -#[cfg(feature = "kms")] -use external_services::kms; use redis_interface as redis; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use router_env::{env, logger}; @@ -13,9 +13,9 @@ use serde::Deserialize; use crate::errors; -#[cfg(feature = "kms")] -pub type Password = kms::KmsValue; -#[cfg(not(feature = "kms"))] +#[cfg(feature = "aws_kms")] +pub type Password = aws_kms::AwsKmsValue; +#[cfg(not(feature = "aws_kms"))] pub type Password = masking::Secret<String>; #[derive(clap::Parser, Default)] @@ -34,8 +34,8 @@ pub struct Settings { pub redis: redis::RedisSettings, pub log: Log, pub drainer: DrainerSettings, - #[cfg(feature = "kms")] - pub kms: kms::KmsConfig, + #[cfg(feature = "aws_kms")] + pub kms: aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, } diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index bf836af71a7..2b6bc22b2e9 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license.workspace = true [features] -kms = ["dep:aws-config", "dep:aws-sdk-kms"] +aws_kms = ["dep:aws-config", "dep:aws-sdk-kms"] email = ["dep:aws-config"] aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = [ "dep:vaultrs" ] diff --git a/crates/external_services/src/kms.rs b/crates/external_services/src/aws_kms.rs similarity index 69% rename from crates/external_services/src/kms.rs rename to crates/external_services/src/aws_kms.rs index 740bca4d821..cf21f36f22b 100644 --- a/crates/external_services/src/kms.rs +++ b/crates/external_services/src/aws_kms.rs @@ -14,18 +14,20 @@ pub mod decrypt; use crate::{consts, metrics}; -static KMS_CLIENT: tokio::sync::OnceCell<KmsClient> = tokio::sync::OnceCell::const_new(); +static AWS_KMS_CLIENT: tokio::sync::OnceCell<AwsKmsClient> = tokio::sync::OnceCell::const_new(); -/// Returns a shared KMS client, or initializes a new one if not previously initialized. +/// Returns a shared AWS KMS client, or initializes a new one if not previously initialized. #[inline] -pub async fn get_kms_client(config: &KmsConfig) -> &'static KmsClient { - KMS_CLIENT.get_or_init(|| KmsClient::new(config)).await +pub async fn get_aws_kms_client(config: &AwsKmsConfig) -> &'static AwsKmsClient { + AWS_KMS_CLIENT + .get_or_init(|| AwsKmsClient::new(config)) + .await } -/// Configuration parameters required for constructing a [`KmsClient`]. +/// Configuration parameters required for constructing a [`AwsKmsClient`]. #[derive(Clone, Debug, Default, serde::Deserialize)] #[serde(default)] -pub struct KmsConfig { +pub struct AwsKmsConfig { /// The AWS key identifier of the KMS key used to encrypt or decrypt data. pub key_id: String, @@ -33,16 +35,16 @@ pub struct KmsConfig { pub region: String, } -/// Client for KMS operations. +/// Client for AWS KMS operations. #[derive(Debug)] -pub struct KmsClient { +pub struct AwsKmsClient { inner_client: Client, key_id: String, } -impl KmsClient { - /// Constructs a new KMS client. - pub async fn new(config: &KmsConfig) -> Self { +impl AwsKmsClient { + /// Constructs a new AWS KMS client. + pub async fn new(config: &AwsKmsConfig) -> Self { let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone())); let sdk_config = aws_config::from_env().region(region_provider).load().await; @@ -56,12 +58,12 @@ impl KmsClient { /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in /// a machine that is able to assume an IAM role. - pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, KmsError> { + pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> { let start = Instant::now(); let data = consts::BASE64_ENGINE .decode(data) .into_report() - .change_context(KmsError::Base64DecodingFailed)?; + .change_context(AwsKmsError::Base64DecodingFailed)?; let ciphertext_blob = Blob::new(data); let decrypt_output = self @@ -74,21 +76,21 @@ impl KmsClient { .map_err(|error| { // Logging using `Debug` representation of the error as the `Display` // representation does not hold sufficient information. - logger::error!(kms_sdk_error=?error, "Failed to KMS decrypt data"); + logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data"); metrics::AWS_KMS_DECRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); error }) .into_report() - .change_context(KmsError::DecryptionFailed)?; + .change_context(AwsKmsError::DecryptionFailed)?; let output = decrypt_output .plaintext - .ok_or(KmsError::MissingPlaintextDecryptionOutput) + .ok_or(AwsKmsError::MissingPlaintextDecryptionOutput) .into_report() .and_then(|blob| { String::from_utf8(blob.into_inner()) .into_report() - .change_context(KmsError::Utf8DecodingFailed) + .change_context(AwsKmsError::Utf8DecodingFailed) })?; let time_taken = start.elapsed(); @@ -101,7 +103,7 @@ impl KmsClient { /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in /// a machine that is able to assume an IAM role. - pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, KmsError> { + pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> { let start = Instant::now(); let plaintext_blob = Blob::new(data.as_ref()); @@ -115,16 +117,16 @@ impl KmsClient { .map_err(|error| { // Logging using `Debug` representation of the error as the `Display` // representation does not hold sufficient information. - logger::error!(kms_sdk_error=?error, "Failed to KMS encrypt data"); + logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data"); metrics::AWS_KMS_ENCRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); error }) .into_report() - .change_context(KmsError::EncryptionFailed)?; + .change_context(AwsKmsError::EncryptionFailed)?; let output = encrypted_output .ciphertext_blob - .ok_or(KmsError::MissingCiphertextEncryptionOutput) + .ok_or(AwsKmsError::MissingCiphertextEncryptionOutput) .into_report() .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?; let time_taken = start.elapsed(); @@ -134,9 +136,9 @@ impl KmsClient { } } -/// Errors that could occur during KMS operations. +/// Errors that could occur during AWS KMS operations. #[derive(Debug, thiserror::Error)] -pub enum KmsError { +pub enum AwsKmsError { /// An error occurred when base64 encoding input data. #[error("Failed to base64 encode input data")] Base64EncodingFailed, @@ -145,33 +147,33 @@ pub enum KmsError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, - /// An error occurred when KMS decrypting input data. - #[error("Failed to KMS decrypt input data")] + /// An error occurred when AWS KMS decrypting input data. + #[error("Failed to AWS KMS decrypt input data")] DecryptionFailed, - /// An error occurred when KMS encrypting input data. - #[error("Failed to KMS encrypt input data")] + /// An error occurred when AWS KMS encrypting input data. + #[error("Failed to AWS KMS encrypt input data")] EncryptionFailed, - /// The KMS decrypted output does not include a plaintext output. - #[error("Missing plaintext KMS decryption output")] + /// The AWS KMS decrypted output does not include a plaintext output. + #[error("Missing plaintext AWS KMS decryption output")] MissingPlaintextDecryptionOutput, - /// The KMS encrypted output does not include a ciphertext output. - #[error("Missing ciphertext KMS encryption output")] + /// The AWS KMS encrypted output does not include a ciphertext output. + #[error("Missing ciphertext AWS KMS encryption output")] MissingCiphertextEncryptionOutput, - /// An error occurred UTF-8 decoding KMS decrypted output. + /// An error occurred UTF-8 decoding AWS KMS decrypted output. #[error("Failed to UTF-8 decode decryption output")] Utf8DecodingFailed, - /// The KMS client has not been initialized. - #[error("The KMS client has not been initialized")] - KmsClientNotInitialized, + /// The AWS KMS client has not been initialized. + #[error("The AWS KMS client has not been initialized")] + AwsKmsClientNotInitialized, } -impl KmsConfig { - /// Verifies that the [`KmsClient`] configuration is usable. +impl AwsKmsConfig { + /// Verifies that the [`AwsKmsClient`] configuration is usable. pub fn validate(&self) -> Result<(), &'static str> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; @@ -185,18 +187,24 @@ impl KmsConfig { } } -/// A wrapper around a KMS value that can be decrypted. +/// A wrapper around a AWS KMS value that can be decrypted. #[derive(Clone, Debug, Default, serde::Deserialize, Eq, PartialEq)] #[serde(transparent)] -pub struct KmsValue(Secret<String>); +pub struct AwsKmsValue(Secret<String>); -impl From<String> for KmsValue { +impl common_utils::ext_traits::ConfigExt for AwsKmsValue { + fn is_empty_after_trim(&self) -> bool { + self.0.peek().is_empty_after_trim() + } +} + +impl From<String> for AwsKmsValue { fn from(value: String) -> Self { Self(Secret::new(value)) } } -impl From<Secret<String>> for KmsValue { +impl From<Secret<String>> for AwsKmsValue { fn from(value: Secret<String>) -> Self { Self(value) } @@ -204,7 +212,7 @@ impl From<Secret<String>> for KmsValue { #[cfg(feature = "hashicorp-vault")] #[async_trait::async_trait] -impl super::hashicorp_vault::decrypt::VaultFetch for KmsValue { +impl super::hashicorp_vault::decrypt::VaultFetch for AwsKmsValue { async fn fetch_inner<En>( self, client: &super::hashicorp_vault::HashiCorpVault, @@ -224,13 +232,7 @@ impl super::hashicorp_vault::decrypt::VaultFetch for KmsValue { >, > + 'a, { - self.0.fetch_inner::<En>(client).await.map(KmsValue) - } -} - -impl common_utils::ext_traits::ConfigExt for KmsValue { - fn is_empty_after_trim(&self) -> bool { - self.0.peek().is_empty_after_trim() + self.0.fetch_inner::<En>(client).await.map(AwsKmsValue) } } @@ -238,44 +240,44 @@ impl common_utils::ext_traits::ConfigExt for KmsValue { mod tests { #![allow(clippy::expect_used)] #[tokio::test] - async fn check_kms_encryption() { + async fn check_aws_kms_encryption() { std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); use super::*; - let config = KmsConfig { - key_id: "YOUR KMS KEY ID".to_string(), + let config = AwsKmsConfig { + key_id: "YOUR AWS KMS KEY ID".to_string(), region: "AWS REGION".to_string(), }; let data = "hello".to_string(); let binding = data.as_bytes(); - let kms_encrypted_fingerprint = KmsClient::new(&config) + let kms_encrypted_fingerprint = AwsKmsClient::new(&config) .await .encrypt(binding) .await - .expect("kms encryption failed"); + .expect("aws kms encryption failed"); println!("{}", kms_encrypted_fingerprint); } #[tokio::test] - async fn check_kms_decrypt() { + async fn check_aws_kms_decrypt() { std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); use super::*; - let config = KmsConfig { - key_id: "YOUR KMS KEY ID".to_string(), + let config = AwsKmsConfig { + key_id: "YOUR AWS KMS KEY ID".to_string(), region: "AWS REGION".to_string(), }; // Should decrypt to hello - let data = "KMS ENCRYPTED CIPHER".to_string(); + let data = "AWS KMS ENCRYPTED CIPHER".to_string(); let binding = data.as_bytes(); - let kms_encrypted_fingerprint = KmsClient::new(&config) + let kms_encrypted_fingerprint = AwsKmsClient::new(&config) .await .decrypt(binding) .await - .expect("kms decryption failed"); + .expect("aws kms decryption failed"); println!("{}", kms_encrypted_fingerprint); } diff --git a/crates/external_services/src/aws_kms/decrypt.rs b/crates/external_services/src/aws_kms/decrypt.rs new file mode 100644 index 00000000000..9abd4fefbef --- /dev/null +++ b/crates/external_services/src/aws_kms/decrypt.rs @@ -0,0 +1,42 @@ +use common_utils::errors::CustomResult; + +use super::*; + +#[async_trait::async_trait] +/// This trait performs in place decryption of the structure on which this is implemented +pub trait AwsKmsDecrypt { + /// The output type of the decryption + type Output; + /// Decrypts the structure given a AWS KMS client + async fn decrypt_inner( + self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> + where + Self: Sized; + + /// Tries to use the Singleton client to decrypt the structure + async fn try_decrypt_inner(self) -> CustomResult<Self::Output, AwsKmsError> + where + Self: Sized, + { + let client = AWS_KMS_CLIENT + .get() + .ok_or(AwsKmsError::AwsKmsClientNotInitialized)?; + self.decrypt_inner(client).await + } +} + +#[async_trait::async_trait] +impl AwsKmsDecrypt for &AwsKmsValue { + type Output = String; + async fn decrypt_inner( + self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + aws_kms_client + .decrypt(self.0.peek()) + .await + .attach_printable("Failed to decrypt AWS KMS value") + } +} diff --git a/crates/external_services/src/kms/decrypt.rs b/crates/external_services/src/kms/decrypt.rs deleted file mode 100644 index 0749745affc..00000000000 --- a/crates/external_services/src/kms/decrypt.rs +++ /dev/null @@ -1,34 +0,0 @@ -use common_utils::errors::CustomResult; - -use super::*; - -#[async_trait::async_trait] -/// This trait performs in place decryption of the structure on which this is implemented -pub trait KmsDecrypt { - /// The output type of the decryption - type Output; - /// Decrypts the structure given a KMS client - async fn decrypt_inner(self, kms_client: &KmsClient) -> CustomResult<Self::Output, KmsError> - where - Self: Sized; - - /// Tries to use the Singleton client to decrypt the structure - async fn try_decrypt_inner(self) -> CustomResult<Self::Output, KmsError> - where - Self: Sized, - { - let client = KMS_CLIENT.get().ok_or(KmsError::KmsClientNotInitialized)?; - self.decrypt_inner(client).await - } -} - -#[async_trait::async_trait] -impl KmsDecrypt for &KmsValue { - type Output = String; - async fn decrypt_inner(self, kms_client: &KmsClient) -> CustomResult<Self::Output, KmsError> { - kms_client - .decrypt(self.0.peek()) - .await - .attach_printable("Failed to decrypt KMS value") - } -} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index bba65873e91..cdabdeb49ae 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -6,15 +6,15 @@ #[cfg(feature = "email")] pub mod email; -#[cfg(feature = "kms")] -pub mod kms; +#[cfg(feature = "aws_kms")] +pub mod aws_kms; pub mod file_storage; #[cfg(feature = "hashicorp-vault")] pub mod hashicorp_vault; /// Crate specific constants -#[cfg(feature = "kms")] +#[cfg(feature = "aws_kms")] pub mod consts { /// General purpose base64 engine pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = @@ -22,20 +22,20 @@ pub mod consts { } /// Metrics for interactions with external systems. -#[cfg(feature = "kms")] +#[cfg(feature = "aws_kms")] pub mod metrics { use router_env::{counter_metric, global_meter, histogram_metric, metrics_context}; metrics_context!(CONTEXT); global_meter!(GLOBAL_METER, "EXTERNAL_SERVICES"); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures - #[cfg(feature = "kms")] - histogram_metric!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for KMS decryption time (in sec) - #[cfg(feature = "kms")] - histogram_metric!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for KMS encryption time (in sec) + #[cfg(feature = "aws_kms")] + histogram_metric!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS decryption time (in sec) + #[cfg(feature = "aws_kms")] + histogram_metric!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS encryption time (in sec) } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f60b0c25e93..9b345217bb5 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -11,12 +11,12 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] aws_s3 = ["external_services/aws_s3"] -kms = ["external_services/kms"] +aws_kms = ["external_services/aws_kms"] hashicorp-vault = ["external_services/hashicorp-vault"] email = ["external_services/email", "olap"] frm = [] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] +release = ["aws_kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap","api_models/olap","dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] diff --git a/crates/router/src/configs.rs b/crates/router/src/configs.rs index 5cb1df0644e..d069c89b82e 100644 --- a/crates/router/src/configs.rs +++ b/crates/router/src/configs.rs @@ -1,7 +1,7 @@ +#[cfg(feature = "aws_kms")] +pub mod aws_kms; mod defaults; #[cfg(feature = "hashicorp-vault")] pub mod hc_vault; -#[cfg(feature = "kms")] -pub mod kms; pub mod settings; mod validations; diff --git a/crates/router/src/configs/aws_kms.rs b/crates/router/src/configs/aws_kms.rs new file mode 100644 index 00000000000..5e37f2a4dd6 --- /dev/null +++ b/crates/router/src/configs/aws_kms.rs @@ -0,0 +1,107 @@ +use common_utils::errors::CustomResult; +use external_services::aws_kms::{decrypt::AwsKmsDecrypt, AwsKmsClient, AwsKmsError}; +use masking::ExposeInterface; + +use crate::configs::settings; + +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::Jwekey { + type Output = Self; + + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + ( + self.vault_encryption_key, + self.rust_locker_encryption_key, + self.vault_private_key, + self.tunnel_private_key, + ) = tokio::try_join!( + aws_kms_client.decrypt(self.vault_encryption_key), + aws_kms_client.decrypt(self.rust_locker_encryption_key), + aws_kms_client.decrypt(self.vault_private_key), + aws_kms_client.decrypt(self.tunnel_private_key), + )?; + Ok(self) + } +} + +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::ActiveKmsSecrets { + type Output = Self; + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + self.jwekey = self + .jwekey + .expose() + .decrypt_inner(aws_kms_client) + .await? + .into(); + Ok(self) + } +} + +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::Database { + type Output = storage_impl::config::Database; + + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + Ok(storage_impl::config::Database { + host: self.host, + port: self.port, + dbname: self.dbname, + username: self.username, + password: self.password.decrypt_inner(aws_kms_client).await?.into(), + pool_size: self.pool_size, + connection_timeout: self.connection_timeout, + queue_strategy: self.queue_strategy, + min_idle: self.min_idle, + max_lifetime: self.max_lifetime, + }) + } +} + +#[cfg(feature = "olap")] +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::PayPalOnboarding { + type Output = Self; + + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + self.client_id = aws_kms_client + .decrypt(self.client_id.expose()) + .await? + .into(); + self.client_secret = aws_kms_client + .decrypt(self.client_secret.expose()) + .await? + .into(); + self.partner_id = aws_kms_client + .decrypt(self.partner_id.expose()) + .await? + .into(); + Ok(self) + } +} + +#[cfg(feature = "olap")] +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::ConnectorOnboarding { + type Output = Self; + + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + self.paypal = self.paypal.decrypt_inner(aws_kms_client).await?; + Ok(self) + } +} diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 7b88c9c2dc7..fc5ba0f55bc 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -1,8 +1,8 @@ use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; -#[cfg(feature = "kms")] -use external_services::kms::KmsValue; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::AwsKmsValue; use super::settings::{ConnectorFields, Password, PaymentMethodType, RequiredFieldFinal}; @@ -6235,12 +6235,12 @@ impl Default for super::settings::RequiredFields { impl Default for super::settings::ApiKeys { fn default() -> Self { Self { - #[cfg(feature = "kms")] - kms_encrypted_hash_key: KmsValue::default(), + #[cfg(feature = "aws_kms")] + kms_encrypted_hash_key: AwsKmsValue::default(), // Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating // hashes of API keys - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] hash_key: String::new(), // Specifies the number of days before API key expiry when email reminders should be sent diff --git a/crates/router/src/configs/kms.rs b/crates/router/src/configs/kms.rs deleted file mode 100644 index 4e236a512ac..00000000000 --- a/crates/router/src/configs/kms.rs +++ /dev/null @@ -1,96 +0,0 @@ -use common_utils::errors::CustomResult; -use external_services::kms::{decrypt::KmsDecrypt, KmsClient, KmsError}; -use masking::ExposeInterface; - -use crate::configs::settings; - -#[async_trait::async_trait] -impl KmsDecrypt for settings::Jwekey { - type Output = Self; - - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - ( - self.vault_encryption_key, - self.rust_locker_encryption_key, - self.vault_private_key, - self.tunnel_private_key, - ) = tokio::try_join!( - kms_client.decrypt(self.vault_encryption_key), - kms_client.decrypt(self.rust_locker_encryption_key), - kms_client.decrypt(self.vault_private_key), - kms_client.decrypt(self.tunnel_private_key), - )?; - Ok(self) - } -} - -#[async_trait::async_trait] -impl KmsDecrypt for settings::ActiveKmsSecrets { - type Output = Self; - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - self.jwekey = self.jwekey.expose().decrypt_inner(kms_client).await?.into(); - Ok(self) - } -} - -#[async_trait::async_trait] -impl KmsDecrypt for settings::Database { - type Output = storage_impl::config::Database; - - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - Ok(storage_impl::config::Database { - host: self.host, - port: self.port, - dbname: self.dbname, - username: self.username, - password: self.password.decrypt_inner(kms_client).await?.into(), - pool_size: self.pool_size, - connection_timeout: self.connection_timeout, - queue_strategy: self.queue_strategy, - min_idle: self.min_idle, - max_lifetime: self.max_lifetime, - }) - } -} - -#[cfg(feature = "olap")] -#[async_trait::async_trait] -impl KmsDecrypt for settings::PayPalOnboarding { - type Output = Self; - - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - self.client_id = kms_client.decrypt(self.client_id.expose()).await?.into(); - self.client_secret = kms_client - .decrypt(self.client_secret.expose()) - .await? - .into(); - self.partner_id = kms_client.decrypt(self.partner_id.expose()).await?.into(); - Ok(self) - } -} - -#[cfg(feature = "olap")] -#[async_trait::async_trait] -impl KmsDecrypt for settings::ConnectorOnboarding { - type Output = Self; - - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - self.paypal = self.paypal.decrypt_inner(kms_client).await?; - Ok(self) - } -} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index dd6eaa104cb..2519455f95a 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -8,13 +8,13 @@ use analytics::ReportConfig; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "email")] use external_services::email::EmailSettings; use external_services::file_storage::FileStorageConfig; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; -#[cfg(feature = "kms")] -use external_services::kms; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; @@ -29,9 +29,9 @@ use crate::{ env::{self, logger, Env}, events::EventsConfig, }; -#[cfg(feature = "kms")] -pub type Password = kms::KmsValue; -#[cfg(not(feature = "kms"))] +#[cfg(feature = "aws_kms")] +pub type Password = aws_kms::AwsKmsValue; +#[cfg(not(feature = "aws_kms"))] pub type Password = masking::Secret<String>; #[derive(clap::Parser, Default)] @@ -53,8 +53,8 @@ pub enum Subcommand { GenerateOpenapiSpec, } -#[cfg(feature = "kms")] -/// Store the decrypted kms secret values for active use in the application +#[cfg(feature = "aws_kms")] +/// Store the decrypted aws kms secret values for active use in the application /// Currently using `StrongSecret` won't have any effect as this struct have smart pointers to heap /// allocations. /// note: we can consider adding such behaviour in the future with custom implementation @@ -88,8 +88,8 @@ pub struct Settings { pub pm_filters: ConnectorFilters, pub bank_config: BankRedirectConfig, pub api_keys: ApiKeys, - #[cfg(feature = "kms")] - pub kms: kms::KmsConfig, + #[cfg(feature = "aws_kms")] + pub kms: aws_kms::AwsKmsConfig, pub file_storage: FileStorageConfig, #[cfg(feature = "hashicorp-vault")] pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, @@ -359,19 +359,19 @@ pub struct RequiredFieldFinal { #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct Secrets { - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] pub jwt_secret: String, - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] pub admin_api_key: String, - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] pub recon_admin_api_key: String, pub master_enc_key: Password, - #[cfg(feature = "kms")] - pub kms_encrypted_jwt_secret: kms::KmsValue, - #[cfg(feature = "kms")] - pub kms_encrypted_admin_api_key: kms::KmsValue, - #[cfg(feature = "kms")] - pub kms_encrypted_recon_admin_api_key: kms::KmsValue, + #[cfg(feature = "aws_kms")] + pub kms_encrypted_jwt_secret: aws_kms::AwsKmsValue, + #[cfg(feature = "aws_kms")] + pub kms_encrypted_admin_api_key: aws_kms::AwsKmsValue, + #[cfg(feature = "aws_kms")] + pub kms_encrypted_recon_admin_api_key: aws_kms::AwsKmsValue, } #[derive(Debug, Deserialize, Clone)] @@ -441,7 +441,7 @@ pub struct Database { pub max_lifetime: Option<u64>, } -#[cfg(not(feature = "kms"))] +#[cfg(not(feature = "aws_kms"))] impl From<Database> for storage_impl::config::Database { fn from(val: Database) -> Self { Self { @@ -596,12 +596,12 @@ pub struct WebhookIgnoreErrorSettings { pub struct ApiKeys { /// Base64-encoded (KMS encrypted) ciphertext of the key used for calculating hashes of API /// keys - #[cfg(feature = "kms")] - pub kms_encrypted_hash_key: kms::KmsValue, + #[cfg(feature = "aws_kms")] + pub kms_encrypted_hash_key: aws_kms::AwsKmsValue, /// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating /// hashes of API keys - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] pub hash_key: String, // Specifies the number of days before API key expiry when email reminders should be sent @@ -712,7 +712,7 @@ impl Settings { #[cfg(feature = "kv_store")] self.drainer.validate()?; self.api_keys.validate()?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] self.kms .validate() .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 910ae754347..a4eb3f3c66e 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -5,7 +5,7 @@ impl super::settings::Secrets { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] { when(self.jwt_secret.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( @@ -20,7 +20,7 @@ impl super::settings::Secrets { })?; } - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] { when(self.kms_encrypted_jwt_secret.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( @@ -131,14 +131,14 @@ impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] return when(self.kms_encrypted_hash_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty when KMS feature is enabled".into(), )) }); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] when(self.hash_key.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty".into(), diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 9bdc493e078..58f95e1371e 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -35,7 +35,7 @@ pub mod user; #[cfg(feature = "olap")] pub mod user_role; pub mod utils; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index f28d845609a..162f8bed0f8 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -2,11 +2,11 @@ use common_utils::date_time; #[cfg(feature = "email")] use diesel_models::{api_keys::ApiKey, enums as storage_enums}; use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms; -#[cfg(not(feature = "kms"))] +#[cfg(not(feature = "aws_kms"))] use masking::ExposeInterface; use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; @@ -30,26 +30,26 @@ const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY"; #[cfg(feature = "email")] const API_KEY_EXPIRY_RUNNER: &str = "API_KEY_EXPIRY_WORKFLOW"; -#[cfg(feature = "kms")] -use external_services::kms::decrypt::KmsDecrypt; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::decrypt::AwsKmsDecrypt; static HASH_KEY: tokio::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> = tokio::sync::OnceCell::const_new(); pub async fn get_hash_key( api_key_config: &settings::ApiKeys, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hc_client: &external_services::hashicorp_vault::HashiCorpVault, ) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> { HASH_KEY .get_or_try_init(|| async { let hash_key = { - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] { api_key_config.kms_encrypted_hash_key.clone() } - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] { masking::Secret::<_, masking::WithType>::new(api_key_config.hash_key.clone()) } @@ -61,14 +61,14 @@ pub async fn get_hash_key( .await .change_context(errors::ApiErrorResponse::InternalServerError)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let hash_key = hash_key - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to KMS decrypt API key hashing key")?; + .attach_printable("Failed to AWS KMS decrypt API key hashing key")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let hash_key = hash_key.expose(); <[u8; PlaintextApiKey::HASH_KEY_LEN]>::try_from( @@ -153,7 +153,7 @@ impl PlaintextApiKey { #[instrument(skip_all)] pub async fn create_api_key( state: AppState, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hc_client: &external_services::hashicorp_vault::HashiCorpVault, api_key: api::CreateApiKeyRequest, @@ -175,8 +175,8 @@ pub async fn create_api_key( let hash_key = get_hash_key( api_key_config, - #[cfg(feature = "kms")] - kms_client, + #[cfg(feature = "aws_kms")] + aws_kms_client, #[cfg(feature = "hashicorp-vault")] hc_client, ) @@ -589,8 +589,8 @@ mod tests { let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); let hash_key = get_hash_key( &settings.api_keys, - #[cfg(feature = "kms")] - external_services::kms::get_kms_client(&settings.kms).await, + #[cfg(feature = "aws_kms")] + external_services::aws_kms::get_aws_kms_client(&settings.kms).await, #[cfg(feature = "hashicorp-vault")] external_services::hashicorp_vault::get_hashicorp_client(&settings.hc_vault) .await diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs index b7effaf63ac..0e452a90f48 100644 --- a/crates/router/src/core/blocklist/utils.rs +++ b/crates/router/src/core/blocklist/utils.rs @@ -1,8 +1,8 @@ use api_models::blocklist as api_blocklist; use common_utils::crypto::{self, SignMessage}; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "kms")] -use external_services::kms; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; use super::{errors, AppState}; use crate::{ @@ -38,15 +38,15 @@ pub async fn delete_entry_from_blocklist( message: "blocklist record with given fingerprint id not found".to_string(), })?; - #[cfg(feature = "kms")] - let decrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let decrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(blocklist_fingerprint.encrypted_fingerprint) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to kms decrypt fingerprint")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; let blocklist_entry = state @@ -184,15 +184,15 @@ pub async fn insert_entry_into_blocklist( message: "fingerprint not found".to_string(), })?; - #[cfg(feature = "kms")] - let decrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let decrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(blocklist_fingerprint.encrypted_fingerprint) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to kms decrypt encrypted fingerprint")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; state diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs index 41699df47a7..b0d06f9fd65 100644 --- a/crates/router/src/core/currency.rs +++ b/crates/router/src/core/currency.rs @@ -17,7 +17,7 @@ pub async fn retrieve_forex( state.conf.forex_api.call_delay, state.conf.forex_api.local_fetch_retry_delay, state.conf.forex_api.local_fetch_retry_count, - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] &state.conf.kms, #[cfg(feature = "hashicorp-vault")] &state.conf.hc_vault, @@ -44,7 +44,7 @@ pub async fn convert_forex( amount, to_currency, from_currency, - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] &state.conf.kms, #[cfg(feature = "hashicorp-vault")] &state.conf.hc_vault, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 9052893d4a9..c7486e827c2 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -221,12 +221,12 @@ pub enum VaultError { } #[derive(Debug, thiserror::Error)] -pub enum KmsError { +pub enum AwsKmsError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, - #[error("Failed to KMS decrypt input data")] + #[error("Failed to AWS KMS decrypt input data")] DecryptionFailed, - #[error("Missing plaintext KMS decryption output")] + #[error("Missing plaintext AWS KMS decryption output")] MissingPlaintextDecryptionOutput, #[error("Failed to UTF-8 decode decryption output")] Utf8DecodingFailed, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 5797fd60da0..4bc0490e7d1 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -603,9 +603,9 @@ pub async fn get_payment_method_from_hs_locker<'a>( locker_choice: Option<api_enums::LockerChoice>, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwekey = &state.conf.jwekey; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwekey = &state.kms_secrets; let payment_method_data = if !locker.mock_locker { @@ -661,9 +661,9 @@ pub async fn call_to_locker_hs<'a>( locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwekey = &state.conf.jwekey; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwekey = &state.kms_secrets; let db = &*state.store; let stored_card_response = if !locker.mock_locker { @@ -722,9 +722,9 @@ pub async fn get_card_from_hs_locker<'a>( locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<payment_methods::Card, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwekey = &state.conf.jwekey; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwekey = &state.kms_secrets; if !locker.mock_locker { @@ -777,9 +777,9 @@ pub async fn delete_card_from_hs_locker<'a>( card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { let locker = &state.conf.locker; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwekey = &state.conf.jwekey; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwekey = &state.kms_secrets; let request = payment_methods::mk_delete_card_request_hs( diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 304091e42ac..12bb5981b1c 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -186,14 +186,14 @@ pub fn get_dotted_jws(jws: encryption::JwsBody) -> String { } pub async fn get_decrypted_response_payload( - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, jwe_body: encryption::JweBody, locker_choice: Option<api_enums::LockerChoice>, ) -> CustomResult<String, errors::VaultError> { let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::Basilisk); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let public_key = match target_locker { api_enums::LockerChoice::Basilisk => jwekey.jwekey.peek().vault_encryption_key.as_bytes(), api_enums::LockerChoice::Tartarus => { @@ -201,16 +201,16 @@ pub async fn get_decrypted_response_payload( } }; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let public_key = match target_locker { api_enums::LockerChoice::Basilisk => jwekey.vault_encryption_key.as_bytes(), api_enums::LockerChoice::Tartarus => jwekey.rust_locker_encryption_key.as_bytes(), }; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = jwekey.vault_private_key.as_bytes(); let jwt = get_dotted_jwe(jwe_body); @@ -237,8 +237,8 @@ pub async fn get_decrypted_response_payload( } pub async fn mk_basilisk_req( - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, jws: &str, locker_choice: api_enums::LockerChoice, ) -> CustomResult<encryption::JweBody, errors::VaultError> { @@ -257,7 +257,7 @@ pub async fn mk_basilisk_req( let payload = utils::Encode::<encryption::JwsBody>::encode_to_vec(&jws_body) .change_context(errors::VaultError::SaveCardFailed)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let public_key = match locker_choice { api_enums::LockerChoice::Basilisk => jwekey.jwekey.peek().vault_encryption_key.as_bytes(), api_enums::LockerChoice::Tartarus => { @@ -265,7 +265,7 @@ pub async fn mk_basilisk_req( } }; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let public_key = match locker_choice { api_enums::LockerChoice::Basilisk => jwekey.vault_encryption_key.as_bytes(), api_enums::LockerChoice::Tartarus => jwekey.rust_locker_encryption_key.as_bytes(), @@ -293,8 +293,8 @@ pub async fn mk_basilisk_req( } pub async fn mk_add_locker_request_hs<'a>( - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, locker: &settings::Locker, payload: &StoreLockerReq<'a>, locker_choice: api_enums::LockerChoice, @@ -302,10 +302,10 @@ pub async fn mk_add_locker_request_hs<'a>( let payload = utils::Encode::<StoreCardReq<'_>>::encode_to_vec(&payload) .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = jwekey.vault_private_key.as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) @@ -463,8 +463,8 @@ pub fn mk_add_card_request( } pub async fn mk_get_card_request_hs( - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, locker: &settings::Locker, customer_id: &str, merchant_id: &str, @@ -480,10 +480,10 @@ pub async fn mk_get_card_request_hs( let payload = utils::Encode::<CardReqBody<'_>>::encode_to_vec(&card_req_body) .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = jwekey.vault_private_key.as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) @@ -540,8 +540,8 @@ pub fn mk_get_card_response(card: GetCardResponse) -> errors::RouterResult<Card> } pub async fn mk_delete_card_request_hs( - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, locker: &settings::Locker, customer_id: &str, merchant_id: &str, @@ -556,10 +556,10 @@ pub async fn mk_delete_card_request_hs( let payload = utils::Encode::<CardReqBody<'_>>::encode_to_vec(&card_req_body) .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = jwekey.vault_private_key.as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 099c266e04f..062c58e056c 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -2,12 +2,12 @@ use api_models::payments as payment_types; use async_trait::async_trait; use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::{IntoReport, Report, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms; #[cfg(feature = "hashicorp-vault")] use masking::ExposeInterface; @@ -258,17 +258,18 @@ async fn create_applepay_session_token( } .await?; - #[cfg(feature = "kms")] - let decrypted_apple_pay_merchant_cert = kms::get_kms_client(&state.conf.kms) - .await - .decrypt(apple_pay_merchant_cert) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Apple pay merchant certificate decryption failed")?; + #[cfg(feature = "aws_kms")] + let decrypted_apple_pay_merchant_cert = + aws_kms::get_aws_kms_client(&state.conf.kms) + .await + .decrypt(apple_pay_merchant_cert) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Apple pay merchant certificate decryption failed")?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let decrypted_apple_pay_merchant_cert_key = - kms::get_kms_client(&state.conf.kms) + aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(apple_pay_merchant_cert_key) .await @@ -277,15 +278,16 @@ async fn create_applepay_session_token( "Apple pay merchant certificate key decryption failed", )?; - #[cfg(feature = "kms")] - let decrypted_merchant_identifier = kms::get_kms_client(&state.conf.kms) - .await - .decrypt(common_merchant_identifier) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Apple pay merchant identifier decryption failed")?; + #[cfg(feature = "aws_kms")] + let decrypted_merchant_identifier = + aws_kms::get_aws_kms_client(&state.conf.kms) + .await + .decrypt(common_merchant_identifier) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Apple pay merchant identifier decryption failed")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_merchant_identifier = common_merchant_identifier; let apple_pay_session_request = get_session_request_for_simplified_apple_pay( @@ -293,10 +295,10 @@ async fn create_applepay_session_token( session_token_data, ); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_apple_pay_merchant_cert = apple_pay_merchant_cert; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_apple_pay_merchant_cert_key = apple_pay_merchant_cert_key; ( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index fe4a7757ecc..5d801063e6e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -13,12 +13,12 @@ use data_models::{ use diesel_models::enums; // TODO : Evaluate all the helper functions () use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms; use josekit::jwe; use masking::{ExposeInterface, PeekInterface}; use openssl::{ @@ -2888,7 +2888,7 @@ pub async fn get_merchant_connector_account( }, )?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = state .kms_secrets .jwekey @@ -2896,7 +2896,7 @@ pub async fn get_merchant_connector_account( .tunnel_private_key .as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = state.conf.jwekey.tunnel_private_key.as_bytes(); let decrypted_mca = services::decrypt_jwe(mca_config.config.as_str(), services::KeyIdCheck::SkipKeyIdCheck, private_key, jwe::RSA_OAEP_256) @@ -3556,14 +3556,14 @@ impl ApplePayData { } .await?; - #[cfg(feature = "kms")] - let cert_data = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let cert_data = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(&apple_pay_ppc) .await .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let cert_data = &apple_pay_ppc; let base64_decode_cert_data = BASE64_ENGINE @@ -3640,14 +3640,14 @@ impl ApplePayData { } .await?; - #[cfg(feature = "kms")] - let decrypted_apple_pay_ppc_key = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let decrypted_apple_pay_ppc_key = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(&apple_pay_ppc_key) .await .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_apple_pay_ppc_key = &apple_pay_ppc_key; // Create PKey objects from EcKey let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes()) diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 151078a6056..486a60f7bc3 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -7,8 +7,8 @@ use common_utils::{ ext_traits::{AsyncExt, Encode}, }; use error_stack::{report, IntoReport, ResultExt}; -#[cfg(feature = "kms")] -use external_services::kms; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; use futures::FutureExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; @@ -869,8 +869,8 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> } if let Some(encoded_hash) = card_number_fingerprint { - #[cfg(feature = "kms")] - let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let encrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms) .await .encrypt(encoded_hash) .await @@ -882,7 +882,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> Some, ); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let encrypted_fingerprint = Some(encoded_hash); if let Some(encrypted_fingerprint) = encrypted_fingerprint { diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 9f70cc6baee..f77d5120812 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -19,8 +19,8 @@ use common_utils::{ }; use data_models::payments::PaymentIntent; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "kms")] -pub use external_services::kms; +#[cfg(feature = "aws_kms")] +pub use external_services::aws_kms; use helpers::PaymentAuthConnectorDataExt; use masking::{ExposeInterface, PeekInterface}; use pm_auth::{ @@ -368,8 +368,8 @@ async fn store_bank_details_in_payment_methods( } .await?; - #[cfg(feature = "kms")] - let pm_auth_key = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let pm_auth_key = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(pm_auth_key) .await diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index bac47b34dce..0ed70e6e0c6 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -2,8 +2,8 @@ pub mod utils; use api_models::verifications::{self, ApplepayMerchantResponse}; use common_utils::{errors::CustomResult, request::RequestContent}; use error_stack::ResultExt; -#[cfg(feature = "kms")] -use external_services::kms; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; use crate::{core::errors::api_error_response, headers, logger, routes::AppState, services}; @@ -13,7 +13,7 @@ pub async fn verify_merchant_creds_for_applepay( state: AppState, _req: &actix_web::HttpRequest, body: verifications::ApplepayMerchantVerificationRequest, - kms_config: &kms::KmsConfig, + kms_config: &aws_kms::AwsKmsConfig, merchant_id: String, ) -> CustomResult< services::ApplicationResponse<ApplepayMerchantResponse>, @@ -27,19 +27,19 @@ pub async fn verify_merchant_creds_for_applepay( let encrypted_key = &state.conf.applepay_merchant_configs.merchant_cert_key; let applepay_endpoint = &state.conf.applepay_merchant_configs.applepay_endpoint; - let applepay_internal_merchant_identifier = kms::get_kms_client(kms_config) + let applepay_internal_merchant_identifier = aws_kms::get_aws_kms_client(kms_config) .await .decrypt(encrypted_merchant_identifier) .await .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; - let cert_data = kms::get_kms_client(kms_config) + let cert_data = aws_kms::get_aws_kms_client(kms_config) .await .decrypt(encrypted_cert) .await .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; - let key_data = kms::get_kms_client(kms_config) + let key_data = aws_kms::get_aws_kms_client(kms_config) .await .decrypt(encrypted_key) .await diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index bb56a173da3..1c80aff4397 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -142,7 +142,7 @@ pub fn mk_app( .service(routes::ConnectorOnboarding::server(state.clone())) } - #[cfg(all(feature = "olap", feature = "kms"))] + #[cfg(all(feature = "olap", feature = "aws_kms"))] { server_app = server_app.service(routes::Verify::server(state.clone())); } diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index d9916f98e74..e058d4f1c1b 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -37,7 +37,7 @@ pub mod routing; pub mod user; #[cfg(feature = "olap")] pub mod user_role; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; @@ -57,7 +57,7 @@ pub use self::app::Forex; pub use self::app::Payouts; #[cfg(all(feature = "olap", feature = "recon"))] pub use self::app::Recon; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] pub use self::app::Verify; pub use self::app::{ ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, ConnectorOnboarding, Customers, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index fb1851af00d..cf859d048dd 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -44,8 +44,9 @@ pub async fn api_key_create( &req, payload, |state, _, payload| async { - #[cfg(feature = "kms")] - let kms_client = external_services::kms::get_kms_client(&state.clone().conf.kms).await; + #[cfg(feature = "aws_kms")] + let aws_kms_client = + external_services::aws_kms::get_aws_kms_client(&state.clone().conf.kms).await; #[cfg(feature = "hashicorp-vault")] let hc_client = external_services::hashicorp_vault::get_hashicorp_client( @@ -56,8 +57,8 @@ pub async fn api_key_create( api_keys::create_api_key( state, - #[cfg(feature = "kms")] - kms_client, + #[cfg(feature = "aws_kms")] + aws_kms_client, #[cfg(feature = "hashicorp-vault")] hc_client, payload, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9e8bee73c28..70cd68dfacc 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1,16 +1,19 @@ use std::sync::Arc; use actix_web::{web, Scope}; -#[cfg(all(feature = "olap", any(feature = "hashicorp-vault", feature = "kms")))] +#[cfg(all( + feature = "olap", + any(feature = "hashicorp-vault", feature = "aws_kms") +))] use analytics::AnalyticsConfig; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "email")] use external_services::email::{ses::AwsSes, EmailService}; use external_services::file_storage::FileStorageInterface; #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms::{self, decrypt::KmsDecrypt}; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] use masking::PeekInterface; use router_env::tracing_actix_web::RequestId; use scheduler::SchedulerInterface; @@ -29,7 +32,7 @@ use super::payouts::*; use super::pm_auth; #[cfg(feature = "olap")] use super::routing as cloud_routing; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "olap")] use super::{ @@ -63,7 +66,7 @@ pub struct AppState { pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<dyn EmailService>, - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] pub kms_secrets: Arc<settings::ActiveKmsSecrets>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] @@ -141,15 +144,15 @@ impl AppState { /// /// Panics if Store can't be created or JWE decryption fails pub async fn with_storage( - #[cfg_attr(not(all(feature = "olap", feature = "kms")), allow(unused_mut))] + #[cfg_attr(not(all(feature = "olap", feature = "aws_kms")), allow(unused_mut))] mut conf: settings::Settings, storage_impl: StorageImpl, shut_down_signal: oneshot::Sender<()>, api_client: Box<dyn crate::services::ApiClient>, ) -> Self { Box::pin(async move { - #[cfg(feature = "kms")] - let kms_client = kms::get_kms_client(&conf.kms).await; + #[cfg(feature = "aws_kms")] + let aws_kms_client = aws_kms::get_aws_kms_client(&conf.kms).await; #[cfg(all(feature = "hashicorp-vault", feature = "olap"))] #[allow(clippy::expect_used)] let hc_client = @@ -207,14 +210,14 @@ impl AppState { } }; - #[cfg(all(feature = "kms", feature = "olap"))] + #[cfg(all(feature = "aws_kms", feature = "olap"))] #[allow(clippy::expect_used)] match conf.analytics { AnalyticsConfig::Clickhouse { .. } => {} AnalyticsConfig::Sqlx { ref mut sqlx } | AnalyticsConfig::CombinedCkh { ref mut sqlx, .. } | AnalyticsConfig::CombinedSqlx { ref mut sqlx, .. } => { - sqlx.password = kms_client + sqlx.password = aws_kms_client .decrypt(&sqlx.password.peek()) .await .expect("Failed to decrypt password") @@ -232,12 +235,12 @@ impl AppState { .expect("Failed to decrypt connector onboarding credentials"); } - #[cfg(all(feature = "kms", feature = "olap"))] + #[cfg(all(feature = "aws_kms", feature = "olap"))] #[allow(clippy::expect_used)] { conf.connector_onboarding = conf .connector_onboarding - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .expect("Failed to decrypt connector onboarding credentials"); } @@ -256,14 +259,14 @@ impl AppState { .expect("Failed to decrypt connector onboarding credentials"); } - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] #[allow(clippy::expect_used)] let kms_secrets = settings::ActiveKmsSecrets { jwekey: conf.jwekey.clone().into(), } - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await - .expect("Failed while performing KMS decryption"); + .expect("Failed while performing AWS KMS decryption"); #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await); @@ -276,7 +279,7 @@ impl AppState { conf: Arc::new(conf), #[cfg(feature = "email")] email_client, - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] kms_secrets: Arc::new(kms_secrets), api_client, event_handler, @@ -934,10 +937,10 @@ impl Gsm { } } -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] pub struct Verify; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] impl Verify { pub fn server(state: AppState) -> Scope { web::scope("/verify") diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 6c3293dba9d..c4d0420a9b5 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -5,9 +5,9 @@ global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses -#[cfg(feature = "kms")] +#[cfg(feature = "aws_kms")] counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures -#[cfg(feature = "kms")] +#[cfg(feature = "aws_kms")] counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures // API Level Metrics diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index c0ed2b442d0..220fde4631f 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -13,14 +13,14 @@ pub mod recon; #[cfg(feature = "email")] pub mod email; -#[cfg(any(feature = "kms", feature = "hashicorp-vault"))] +#[cfg(any(feature = "aws_kms", feature = "hashicorp-vault"))] use data_models::errors::StorageError; use data_models::errors::StorageResult; use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms::{self, decrypt::KmsDecrypt}; use masking::{PeekInterface, StrongSecret}; #[cfg(feature = "kv_store")] use storage_impl::KVRouterStore; @@ -45,8 +45,8 @@ pub async fn get_store( shut_down_signal: oneshot::Sender<()>, test_transaction: bool, ) -> StorageResult<Store> { - #[cfg(feature = "kms")] - let kms_client = kms::get_kms_client(&config.kms).await; + #[cfg(feature = "aws_kms")] + let aws_kms_client = aws_kms::get_aws_kms_client(&config.kms).await; #[cfg(feature = "hashicorp-vault")] let hc_client = external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) @@ -62,9 +62,9 @@ pub async fn get_store( .change_context(StorageError::InitializationError) .attach_printable("Failed to fetch data from hashicorp vault")?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let master_config = master_config - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to decrypt master database config")?; @@ -79,17 +79,17 @@ pub async fn get_store( .change_context(StorageError::InitializationError) .attach_printable("Failed to fetch data from hashicorp vault")?; - #[cfg(all(feature = "olap", feature = "kms"))] + #[cfg(all(feature = "olap", feature = "aws_kms"))] let replica_config = replica_config - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to decrypt replica database config")?; let master_enc_key = get_master_enc_key( config, - #[cfg(feature = "kms")] - kms_client, + #[cfg(feature = "aws_kms")] + aws_kms_client, #[cfg(feature = "hashicorp-vault")] hc_client, ) @@ -128,7 +128,7 @@ pub async fn get_store( #[allow(clippy::expect_used)] async fn get_master_enc_key( conf: &crate::configs::settings::Settings, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hc_client: &external_services::hashicorp_vault::HashiCorpVault, ) -> StrongSecret<Vec<u8>> { @@ -140,10 +140,10 @@ async fn get_master_enc_key( .await .expect("Failed to fetch master enc key"); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let master_enc_key = masking::Secret::<_, masking::WithType>::new( master_enc_key - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .expect("Failed to decrypt master enc key"), ); diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 221106612f3..308ceb2672b 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -3,10 +3,10 @@ use api_models::{payment_methods::PaymentMethodListRequest, payments}; use async_trait::async_trait; use common_utils::date_time; use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms::{self, decrypt::KmsDecrypt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; #[cfg(feature = "hashicorp-vault")] use masking::ExposeInterface; @@ -225,8 +225,8 @@ where let config = state.conf(); api_keys::get_hash_key( &config.api_keys, - #[cfg(feature = "kms")] - kms::get_kms_client(&config.kms).await, + #[cfg(feature = "aws_kms")] + aws_kms::get_aws_kms_client(&config.kms).await, #[cfg(feature = "hashicorp-vault")] external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) .await @@ -289,22 +289,22 @@ static ADMIN_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = pub async fn get_admin_api_key( secrets: &settings::Secrets, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hc_client: &external_services::hashicorp_vault::HashiCorpVault, ) -> RouterResult<&'static StrongSecret<String>> { ADMIN_API_KEY .get_or_try_init(|| async { - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let admin_api_key = secrets.admin_api_key.clone(); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let admin_api_key = secrets .kms_encrypted_admin_api_key - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to KMS decrypt admin API key")?; + .attach_printable("Failed to AWS KMS decrypt admin API key")?; #[cfg(feature = "hashicorp-vault")] let admin_api_key = masking::Secret::new(admin_api_key) @@ -368,8 +368,8 @@ where let admin_api_key = get_admin_api_key( &conf.secrets, - #[cfg(feature = "kms")] - kms::get_kms_client(&conf.kms).await, + #[cfg(feature = "aws_kms")] + aws_kms::get_aws_kms_client(&conf.kms).await, #[cfg(feature = "hashicorp-vault")] external_services::hashicorp_vault::get_hashicorp_client(&conf.hc_vault) .await @@ -873,19 +873,19 @@ static JWT_SECRET: tokio::sync::OnceCell<StrongSecret<String>> = tokio::sync::On pub async fn get_jwt_secret( secrets: &settings::Secrets, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, ) -> RouterResult<&'static StrongSecret<String>> { JWT_SECRET .get_or_try_init(|| async { - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwt_secret = secrets .kms_encrypted_jwt_secret - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to KMS decrypt JWT secret")?; + .attach_printable("Failed to AWS KMS decrypt JWT secret")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwt_secret = secrets.jwt_secret.clone(); Ok(StrongSecret::new(jwt_secret)) @@ -900,8 +900,8 @@ where let conf = state.conf(); let secret = get_jwt_secret( &conf.secrets, - #[cfg(feature = "kms")] - kms::get_kms_client(&conf.kms).await, + #[cfg(feature = "aws_kms")] + aws_kms::get_aws_kms_client(&conf.kms).await, ) .await? .peek() @@ -972,11 +972,11 @@ static RECON_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = #[cfg(feature = "recon")] pub async fn get_recon_admin_api_key( secrets: &settings::Secrets, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] kms_client: &aws_kms::AwsKmsClient, ) -> RouterResult<&'static StrongSecret<String>> { RECON_API_KEY .get_or_try_init(|| async { - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let recon_admin_api_key = secrets .kms_encrypted_recon_admin_api_key .decrypt_inner(kms_client) @@ -984,7 +984,7 @@ pub async fn get_recon_admin_api_key( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to KMS decrypt recon admin API key")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let recon_admin_api_key = secrets.recon_admin_api_key.clone(); Ok(StrongSecret::new(recon_admin_api_key)) @@ -1012,8 +1012,8 @@ where let admin_api_key = get_recon_admin_api_key( &conf.secrets, - #[cfg(feature = "kms")] - kms::get_kms_client(&conf.kms).await, + #[cfg(feature = "aws_kms")] + aws_kms::get_aws_kms_client(&conf.kms).await, ) .await?; diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rs index b69a2158391..08db52e4020 100644 --- a/crates/router/src/services/jwt.rs +++ b/crates/router/src/services/jwt.rs @@ -26,8 +26,8 @@ where { let jwt_secret = authentication::get_jwt_secret( &settings.secrets, - #[cfg(feature = "kms")] - external_services::kms::get_kms_client(&settings.kms).await, + #[cfg(feature = "aws_kms")] + external_services::aws_kms::get_aws_kms_client(&settings.kms).await, ) .await .change_context(UserErrors::InternalServerError) diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index a01f2520b6a..057805a76f0 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -4,10 +4,10 @@ use api_models::enums; use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt}; use currency_conversion::types::{CurrencyFactors, ExchangeRates}; use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::{self, decrypt::VaultFetch}; -#[cfg(feature = "kms")] -use external_services::kms; use masking::PeekInterface; use once_cell::sync::Lazy; use redis_interface::DelReply; @@ -65,8 +65,8 @@ pub enum ForexCacheError { LocalWriteError, #[error("Json Parsing error")] ParsingError, - #[error("Kms decryption error")] - KmsDecryptionFailed, + #[error("Aws Kms decryption error")] + AwsKmsDecryptionFailed, #[error("Error connecting to redis")] RedisConnectionError, #[error("Not able to release write lock")] @@ -128,7 +128,7 @@ async fn waited_fetch_and_update_caches( state: &AppState, local_fetch_retry_delay: u64, local_fetch_retry_count: u64, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -151,8 +151,8 @@ async fn waited_fetch_and_update_caches( successive_fetch_and_save_forex( state, None, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -192,7 +192,7 @@ pub async fn get_forex_rates( call_delay: i64, local_fetch_retry_delay: u64, local_fetch_retry_count: u64, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -203,8 +203,8 @@ pub async fn get_forex_rates( state, call_delay, local_rates, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -220,8 +220,8 @@ pub async fn get_forex_rates( call_delay, local_fetch_retry_delay, local_fetch_retry_count, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -234,7 +234,7 @@ async fn handler_local_no_data( call_delay: i64, _local_fetch_retry_delay: u64, _local_fetch_retry_count: u64, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -244,8 +244,8 @@ async fn handler_local_no_data( state, data, call_delay, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -256,8 +256,8 @@ async fn handler_local_no_data( Ok(successive_fetch_and_save_forex( state, None, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -268,8 +268,8 @@ async fn handler_local_no_data( Ok(successive_fetch_and_save_forex( state, None, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -281,7 +281,7 @@ async fn handler_local_no_data( async fn successive_fetch_and_save_forex( state: &AppState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -292,8 +292,8 @@ async fn successive_fetch_and_save_forex( } let api_rates = fetch_forex_rates( state, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -305,8 +305,8 @@ async fn successive_fetch_and_save_forex( logger::error!(?err); let secondary_api_rates = fallback_fetch_forex_rates( state, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -351,7 +351,7 @@ async fn fallback_forex_redis_check( state: &AppState, redis_data: FxExchangeRatesCacheEntry, call_delay: i64, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -367,8 +367,8 @@ async fn fallback_forex_redis_check( successive_fetch_and_save_forex( state, Some(redis_data), - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -381,7 +381,7 @@ async fn handler_local_expired( state: &AppState, call_delay: i64, local_rates: FxExchangeRatesCacheEntry, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -400,8 +400,8 @@ async fn handler_local_expired( successive_fetch_and_save_forex( state, Some(local_rates), - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -415,8 +415,8 @@ async fn handler_local_expired( successive_fetch_and_save_forex( state, Some(local_rates), - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -427,7 +427,7 @@ async fn handler_local_expired( async fn fetch_forex_rates( state: &AppState, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, @@ -436,7 +436,7 @@ async fn fetch_forex_rates( #[cfg(feature = "hashicorp-vault")] let client = hashicorp_vault::get_hashicorp_client(hc_config) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; #[cfg(not(feature = "hashicorp-vault"))] let output = state.conf.forex_api.api_key.clone(); @@ -448,19 +448,19 @@ async fn fetch_forex_rates( .clone() .fetch_inner::<hashicorp_vault::Kv2>(client) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; Ok::<_, error_stack::Report<ForexCacheError>>(output) } .await?; - #[cfg(feature = "kms")] - let forex_api_key = kms::get_kms_client(kms_config) + #[cfg(feature = "aws_kms")] + let forex_api_key = aws_kms::get_aws_kms_client(aws_kms_config) .await .decrypt(forex_api_key.peek()) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let forex_api_key = forex_api_key.peek(); let forex_url: String = format!("{}{}{}", FOREX_BASE_URL, forex_api_key, FOREX_BASE_CURRENCY); @@ -516,7 +516,7 @@ async fn fetch_forex_rates( pub async fn fallback_fetch_forex_rates( state: &AppState, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -524,7 +524,7 @@ pub async fn fallback_fetch_forex_rates( #[cfg(feature = "hashicorp-vault")] let client = hashicorp_vault::get_hashicorp_client(hc_config) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; #[cfg(not(feature = "hashicorp-vault"))] let output = state.conf.forex_api.fallback_api_key.clone(); @@ -536,19 +536,19 @@ pub async fn fallback_fetch_forex_rates( .clone() .fetch_inner::<hashicorp_vault::Kv2>(client) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; Ok::<_, error_stack::Report<ForexCacheError>>(output) } .await?; - #[cfg(feature = "kms")] - let fallback_forex_api_key = kms::get_kms_client(kms_config) + #[cfg(feature = "aws_kms")] + let fallback_forex_api_key = aws_kms::get_aws_kms_client(aws_kms_config) .await .decrypt(fallback_api_key.peek()) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let fallback_forex_api_key = fallback_api_key.peek(); let fallback_forex_url: String = @@ -691,7 +691,7 @@ pub async fn convert_currency( amount: i64, to_currency: String, from_currency: String, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> { @@ -700,8 +700,8 @@ pub async fn convert_currency( state.conf.forex_api.call_delay, state.conf.forex_api.local_fetch_retry_delay, state.conf.forex_api.local_fetch_retry_count, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) diff --git a/crates/scheduler/src/configs/settings.rs b/crates/scheduler/src/configs/settings.rs index 723ef81e70c..0135c9dcf45 100644 --- a/crates/scheduler/src/configs/settings.rs +++ b/crates/scheduler/src/configs/settings.rs @@ -1,11 +1,5 @@ -#[cfg(feature = "kms")] -use external_services::kms; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use serde::Deserialize; -#[cfg(feature = "kms")] -pub type Password = kms::KmsValue; -#[cfg(not(feature = "kms"))] -pub type Password = masking::Secret<String>; #[derive(Debug, Clone, Deserialize)] #[serde(default)]
2024-01-04T20:00:07Z
## 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 renames `kms` feature flag to `aws_kms`, `kms` files to `aws_kms` and the components of kms to include `aws` as its prefix. This change is done so that current kms encryption is distinguishable, especially if in future new encryption implementations like a AWS KMS alternative is integrated. ### 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)? --> Renaming types so just a basic sanity test 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
892b04f805c219e2cf7cbe5736aef19909e986f7
juspay/hyperswitch
juspay__hyperswitch-3106
Bug: [FEATURE] Add missing routing features to default feature list and release feature list for Hyperswitch Router ### Feature Description Add routing features like business profile routing as well as connector choice mca id to the default feature lit as well as the release feature list. ### Possible Implementation Add missing features to the default and release feature lists ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Makefile b/Makefile index 9b62b3c5c99..780d5a993c9 100644 --- a/Makefile +++ b/Makefile @@ -9,6 +9,10 @@ eq = $(if $(or $(1),$(2)),$(and $(findstring $(1),$(2)),\ $(findstring $(2),$(1))),1) + +ROOT_DIR_WITH_SLASH := $(dir $(realpath $(lastword $(MAKEFILE_LIST)))) +ROOT_DIR := $(realpath $(ROOT_DIR_WITH_SLASH)) + # # = Targets # @@ -67,6 +71,14 @@ fmt : clippy : cargo clippy --all-features --all-targets -- -D warnings +# Build the DSL crate as a WebAssembly JS library +# +# Usage : +# make euclid-wasm + +euclid-wasm: + wasm-pack build --target web --out-dir $(ROOT_DIR)/wasm --out-name euclid $(ROOT_DIR)/crates/euclid_wasm -- --features dummy_connector + # Run Rust tests of project. # # Usage : @@ -93,4 +105,4 @@ precommit : fmt clippy test hack: - cargo hack check --workspace --each-feature --all-targets \ No newline at end of file + cargo hack check --workspace --each-feature --all-targets diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index 8c96a7f67da..51288a9d0fe 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -11,6 +11,7 @@ crate-type = ["cdylib"] [features] default = ["connector_choice_bcompat"] +release = ["connector_choice_bcompat", "connector_choice_mca_id"] connector_choice_bcompat = ["api_models/connector_choice_bcompat"] connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connector_choice_mca_id", "kgraph_utils/connector_choice_mca_id"] dummy_connector = ["kgraph_utils/dummy_connector"] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index b2f7f8b94a9..13324aa59a2 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -9,14 +9,14 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "profile_specific_fallback_routing", "retry", "frm"] +default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config", "olap"] frm = [] basilisk = ["kms"] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "profile_specific_fallback_routing"] +release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"]
2023-12-11T12:11:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds required routing features to the release feature list for Hyperswitch and also updates the Makefile with a command to build the euclid WASM. ### 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). --> Filling in missing features to be enabled by default. ## 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)? --> Local cargo build ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
151a30f4eed10924cd93bf7f4f66976af0ab8314
juspay/hyperswitch
juspay__hyperswitch-3227
Bug: [FEATURE] : Billwerk payments integration ### Feature Description Billwerk Payments is a payment gateway provider focused on Northern Europe countries. ### Possible Implementation Product: [https://www.billwerk.plus/payments/](https://www.billwerk.plus/payments/) Docs: [https://docs.reepay.com/](https://docs.reepay.com/) ### 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 81cd78f7244..ee868beb092 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -170,6 +170,7 @@ applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +billwerk.base_url = "https://api.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" diff --git a/config/development.toml b/config/development.toml index 66ed76c8f3c..8d18e63122f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -97,6 +97,7 @@ cards = [ "authorizedotnet", "bambora", "bankofamerica", + "billwerk", "bitpay", "bluesnap", "boku", @@ -165,6 +166,7 @@ applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +billwerk.base_url = "https://api.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 7677fc4582d..ceb00ff212e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -104,6 +104,7 @@ applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +billwerk.base_url = "https://api.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" @@ -176,6 +177,7 @@ cards = [ "authorizedotnet", "bambora", "bankofamerica", + "billwerk", "bitpay", "bluesnap", "boku", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index f712871abe1..b29377886d5 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -78,6 +78,7 @@ pub enum Connector { Authorizedotnet, Bambora, Bankofamerica, + // Billwerk, Added as template code for future usage Bitpay, Bluesnap, Boku, @@ -165,6 +166,7 @@ impl Connector { | Self::Authorizedotnet | Self::Bambora | Self::Bankofamerica + // | Self::Billwerk Added as template code for future usage | Self::Bitpay | Self::Bluesnap | Self::Boku @@ -221,6 +223,7 @@ impl Connector { | Self::Authorizedotnet | Self::Bambora | Self::Bankofamerica + // | Self::Billwerk Added as template for future usage | Self::Bitpay | Self::Bluesnap | Self::Boku diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 89ca80e72b3..65842a4203d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -115,6 +115,7 @@ pub enum RoutableConnectors { Airwallex, Authorizedotnet, Bankofamerica, + // Billwerk, Added as template code for future usage Bitpay, Bambora, Bluesnap, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 2ef80f8f2f6..74317319f50 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -116,6 +116,7 @@ pub struct ConnectorConfig { pub airwallex: Option<ConnectorTomlConfig>, pub authorizedotnet: Option<ConnectorTomlConfig>, pub bankofamerica: Option<ConnectorTomlConfig>, + pub billwerk: Option<ConnectorTomlConfig>, pub bitpay: Option<ConnectorTomlConfig>, pub bluesnap: Option<ConnectorTomlConfig>, pub boku: Option<ConnectorTomlConfig>, @@ -227,6 +228,7 @@ impl ConnectorConfig { Connector::Airwallex => Ok(connector_data.airwallex), Connector::Authorizedotnet => Ok(connector_data.authorizedotnet), Connector::Bankofamerica => Ok(connector_data.bankofamerica), + // Connector::Billwerk => Ok(connector_data.billwerk), Added as template code for future usage Connector::Bitpay => Ok(connector_data.bitpay), Connector::Bluesnap => Ok(connector_data.bluesnap), Connector::Boku => Ok(connector_data.boku), diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 2f87c5c21d7..d92812cee40 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -480,6 +480,7 @@ pub struct Connectors { pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bankofamerica: ConnectorParams, + pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index eccdf3f9ddf..d786ed4e31b 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -4,6 +4,7 @@ pub mod airwallex; pub mod authorizedotnet; pub mod bambora; pub mod bankofamerica; +pub mod billwerk; pub mod bitpay; pub mod bluesnap; pub mod boku; @@ -60,15 +61,15 @@ pub mod zen; pub use self::dummyconnector::DummyConnector; pub use self::{ aci::Aci, adyen::Adyen, airwallex::Airwallex, authorizedotnet::Authorizedotnet, - bambora::Bambora, bankofamerica::Bankofamerica, bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, - braintree::Braintree, cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, - cryptopay::Cryptopay, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte, - globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, helcim::Helcim, - iatapay::Iatapay, klarna::Klarna, mollie::Mollie, multisafepay::Multisafepay, - nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, - payeezy::Payeezy, payme::Payme, paypal::Paypal, payu::Payu, placetopay::Placetopay, - powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, 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, + bambora::Bambora, bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, + bluesnap::Bluesnap, boku::Boku, braintree::Braintree, cashtocode::Cashtocode, + checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay, cybersource::Cybersource, + dlocal::Dlocal, fiserv::Fiserv, forte::Forte, globalpay::Globalpay, globepay::Globepay, + gocardless::Gocardless, helcim::Helcim, iatapay::Iatapay, klarna::Klarna, mollie::Mollie, + multisafepay::Multisafepay, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, + opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, paypal::Paypal, payu::Payu, + placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, + 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, }; diff --git a/crates/router/src/connector/billwerk.rs b/crates/router/src/connector/billwerk.rs new file mode 100644 index 00000000000..c7d81e06c32 --- /dev/null +++ b/crates/router/src/connector/billwerk.rs @@ -0,0 +1,561 @@ +pub mod transformers; + +use std::fmt::Debug; + +use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; +use transformers as billwerk; + +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(Debug, Clone)] +pub struct Billwerk; + +impl api::Payment for Billwerk {} +impl api::PaymentSession for Billwerk {} +impl api::ConnectorAccessToken for Billwerk {} +impl api::MandateSetup for Billwerk {} +impl api::PaymentAuthorize for Billwerk {} +impl api::PaymentSync for Billwerk {} +impl api::PaymentCapture for Billwerk {} +impl api::PaymentVoid for Billwerk {} +impl api::Refund for Billwerk {} +impl api::RefundExecute for Billwerk {} +impl api::RefundSync for Billwerk {} +impl api::PaymentToken for Billwerk {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Billwerk +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Billwerk +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 Billwerk { + fn id(&self) -> &'static str { + "billwerk" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.billwerk.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let auth = billwerk::BillwerkAuthType::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: billwerk::BillwerkErrorResponse = res + .response + .parse_struct("BillwerkErrorResponse") + .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 Billwerk { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Billwerk +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Billwerk +{ +} + +impl + ConnectorIntegration< + api::SetupMandate, + types::SetupMandateRequestData, + types::PaymentsResponseData, + > for Billwerk +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Billwerk +{ + 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 connector_router_data = billwerk::BillwerkRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = billwerk::BillwerkPaymentsRequest::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: billwerk::BillwerkPaymentsResponse = res + .response + .parse_struct("Billwerk 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 Billwerk +{ + 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: billwerk::BillwerkPaymentsResponse = res + .response + .parse_struct("billwerk 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 Billwerk +{ + 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: billwerk::BillwerkPaymentsResponse = res + .response + .parse_struct("Billwerk 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 Billwerk +{ +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Billwerk +{ + 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 connector_router_data = billwerk::BillwerkRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = billwerk::BillwerkRefundRequest::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: billwerk::RefundResponse = res + .response + .parse_struct("billwerk 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 Billwerk { + 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: billwerk::RefundResponse = res + .response + .parse_struct("billwerk 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 Billwerk { + fn get_webhook_object_reference_id( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs new file mode 100644 index 00000000000..c6f025b7898 --- /dev/null +++ b/crates/router/src/connector/billwerk/transformers.rs @@ -0,0 +1,244 @@ +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + connector::utils::PaymentsAuthorizeRequestData, + core::errors, + types::{self, api, storage::enums}, +}; + +//TODO: Fill the struct with respective fields +pub struct BillwerkRouterData<T> { + pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for BillwerkRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (_currency_unit, _currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Ok(Self { + amount, + router_data: item, + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct BillwerkPaymentsRequest { + amount: i64, + card: BillwerkCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct BillwerkCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + api::PaymentMethodData::Card(req_card) => { + let card = BillwerkCard { + 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, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct BillwerkAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for BillwerkAuthType { + 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 BillwerkPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<BillwerkPaymentStatus> for enums::AttemptStatus { + fn from(item: BillwerkPaymentStatus) -> Self { + match item { + BillwerkPaymentStatus::Succeeded => Self::Charged, + BillwerkPaymentStatus::Failed => Self::Failure, + BillwerkPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BillwerkPaymentsResponse { + status: BillwerkPaymentStatus, + id: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, BillwerkPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BillwerkPaymentsResponse, + 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, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct BillwerkRefundRequest { + pub amount: i64, +} + +impl<F> TryFrom<&BillwerkRouterData<&types::RefundsRouterData<F>>> for BillwerkRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BillwerkRouterData<&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 BillwerkErrorResponse { + 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 2f546cfa5ac..a4be66242ee 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1739,6 +1739,10 @@ pub(crate) fn validate_auth_and_metadata_type( bankofamerica::transformers::BankOfAmericaAuthType::try_from(val)?; Ok(()) } + // api_enums::Connector::Billwerk => { + // billwerk::transformers::BillwerkAuthType::try_from(val)?; + // Ok(()) + // } Added as template code for future usage api_enums::Connector::Bitpay => { bitpay::transformers::BitpayAuthType::try_from(val)?; Ok(()) diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index fe4a504861d..6c952dc2593 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -145,9 +145,9 @@ impl<const T: u8> } default_imp_for_complete_authorize!( - connector::Threedsecureio, connector::Aci, connector::Adyen, + connector::Billwerk, connector::Bitpay, connector::Boku, connector::Cashtocode, @@ -176,6 +176,7 @@ default_imp_for_complete_authorize!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -211,13 +212,13 @@ impl<const T: u8> { } default_imp_for_webhook_source_verification!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Braintree, @@ -257,6 +258,7 @@ default_imp_for_webhook_source_verification!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -294,13 +296,13 @@ impl<const T: u8> } default_imp_for_create_customer!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -338,6 +340,7 @@ default_imp_for_create_customer!( connector::Shift4, connector::Signifyd, connector::Square, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -377,11 +380,11 @@ impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnec } default_imp_for_connector_redirect_response!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Bitpay, connector::Bankofamerica, + connector::Billwerk, connector::Boku, connector::Cashtocode, connector::Coinbase, @@ -410,6 +413,7 @@ default_imp_for_connector_redirect_response!( connector::Signifyd, connector::Square, connector::Stax, + connector::Threedsecureio, connector::Tsys, connector::Volt, connector::Wise, @@ -429,13 +433,13 @@ macro_rules! default_imp_for_connector_request_id { impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {} default_imp_for_connector_request_id!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -474,6 +478,7 @@ default_imp_for_connector_request_id!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -514,13 +519,13 @@ impl<const T: u8> } default_imp_for_accept_dispute!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -560,6 +565,7 @@ default_imp_for_accept_dispute!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -619,13 +625,13 @@ impl<const T: u8> } default_imp_for_file_upload!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -663,6 +669,7 @@ default_imp_for_file_upload!( connector::Signifyd, connector::Square, connector::Stax, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -701,13 +708,13 @@ impl<const T: u8> } default_imp_for_submit_evidence!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -745,6 +752,7 @@ default_imp_for_submit_evidence!( connector::Signifyd, connector::Square, connector::Stax, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -783,13 +791,13 @@ impl<const T: u8> } default_imp_for_defend_dispute!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -828,6 +836,7 @@ default_imp_for_defend_dispute!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -866,11 +875,11 @@ impl<const T: u8> } default_imp_for_pre_processing_steps!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -905,6 +914,7 @@ default_imp_for_pre_processing_steps!( connector::Signifyd, connector::Square, connector::Stax, + connector::Threedsecureio, connector::Tsys, connector::Volt, connector::Wise, @@ -925,12 +935,12 @@ macro_rules! default_imp_for_payouts { impl<const T: u8> api::Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -971,6 +981,7 @@ default_imp_for_payouts!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1008,12 +1019,12 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_create!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1054,6 +1065,7 @@ default_imp_for_payouts_create!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1094,12 +1106,12 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_eligibility!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1140,6 +1152,7 @@ default_imp_for_payouts_eligibility!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1177,12 +1190,12 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_fulfill!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1223,6 +1236,7 @@ default_imp_for_payouts_fulfill!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1260,12 +1274,12 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_cancel!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1306,6 +1320,7 @@ default_imp_for_payouts_cancel!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1343,13 +1358,13 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_quote!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1390,6 +1405,7 @@ default_imp_for_payouts_quote!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1427,13 +1443,13 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_recipient!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1474,6 +1490,7 @@ default_imp_for_payouts_recipient!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1510,13 +1527,13 @@ impl<const T: u8> } default_imp_for_approve!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1557,6 +1574,7 @@ default_imp_for_approve!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1594,13 +1612,13 @@ impl<const T: u8> } default_imp_for_reject!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1641,6 +1659,7 @@ default_imp_for_reject!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1662,13 +1681,13 @@ macro_rules! default_imp_for_fraud_check { impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {} default_imp_for_fraud_check!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1707,6 +1726,7 @@ default_imp_for_fraud_check!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1746,13 +1766,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_sale!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1791,6 +1811,7 @@ default_imp_for_frm_sale!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1830,13 +1851,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_checkout!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1875,6 +1896,7 @@ default_imp_for_frm_checkout!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1914,13 +1936,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_transaction!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1959,6 +1981,7 @@ default_imp_for_frm_transaction!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1998,13 +2021,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_fulfillment!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -2043,6 +2066,7 @@ default_imp_for_frm_fulfillment!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -2082,13 +2106,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_record_return!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -2127,6 +2151,7 @@ default_imp_for_frm_record_return!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -2164,13 +2189,13 @@ impl<const T: u8> } default_imp_for_incremental_authorization!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -2210,6 +2235,7 @@ default_imp_for_incremental_authorization!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -2245,13 +2271,13 @@ impl<const T: u8> { } default_imp_for_revoking_mandates!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -2290,6 +2316,7 @@ default_imp_for_revoking_mandates!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -2373,6 +2400,7 @@ default_imp_for_connector_authentication!( connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index cd9eee46eec..95a0989ac2b 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -328,6 +328,7 @@ impl ConnectorData { enums::Connector::Authorizedotnet => Ok(Box::new(&connector::Authorizedotnet)), enums::Connector::Bambora => Ok(Box::new(&connector::Bambora)), enums::Connector::Bankofamerica => Ok(Box::new(&connector::Bankofamerica)), + // enums::Connector::Billwerk => Ok(Box::new(&connector::Billwerk)), Added as template code for future usage enums::Connector::Bitpay => Ok(Box::new(&connector::Bitpay)), enums::Connector::Bluesnap => Ok(Box::new(&connector::Bluesnap)), enums::Connector::Boku => Ok(Box::new(&connector::Boku)), diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 29774be91af..2f0c9479914 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -188,6 +188,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Authorizedotnet => Self::Authorizedotnet, api_enums::Connector::Bambora => Self::Bambora, api_enums::Connector::Bankofamerica => Self::Bankofamerica, + // api_enums::Connector::Billwerk => Self::Billwerk, Added as template code for future usage api_enums::Connector::Bitpay => Self::Bitpay, api_enums::Connector::Bluesnap => Self::Bluesnap, api_enums::Connector::Boku => Self::Boku, diff --git a/crates/router/tests/connectors/billwerk.rs b/crates/router/tests/connectors/billwerk.rs new file mode 100644 index 00000000000..1dec066e5d2 --- /dev/null +++ b/crates/router/tests/connectors/billwerk.rs @@ -0,0 +1,421 @@ +use masking::Secret; +use router::types::{self, api, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct BillwerkTest; +impl ConnectorActions for BillwerkTest {} +impl utils::Connector for BillwerkTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Billwerk; + types::api::ConnectorData { + connector: Box::new(&Billwerk), + // Added as Dummy connector as template code is added for future usage + connector_name: types::Connector::DummyConnector1, + get_token: types::api::GetToken::Connector, + merchant_connector_id: None, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .billwerk + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "billwerk".to_string() + } +} + +static CONNECTOR: BillwerkTest = BillwerkTest {}; + +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: router::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: router::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 scenerios +// 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: types::api::PaymentMethodData::Card(api::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: types::api::PaymentMethodData::Card(api::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: types::api::PaymentMethodData::Card(api::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/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 8db743d6098..eb428a36cb9 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -13,6 +13,8 @@ mod authorizedotnet; mod bambora; #[cfg(feature = "dummy_connector")] mod bankofamerica; +#[cfg(feature = "dummy_connector")] +mod billwerk; mod bitpay; mod bluesnap; mod boku; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 3f78ff7f491..bd17f279c2d 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -198,3 +198,7 @@ key1= "Trankey" [threedsecureio] api_key="API Key" + + +[billwerk] +api_key="API Key" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index a2753a2c517..34a5e35928d 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -18,6 +18,7 @@ pub struct ConnectorAuthentication { pub authorizedotnet: Option<BodyKey>, pub bambora: Option<BodyKey>, pub bankofamerica: Option<SignatureKey>, + pub billwerk: Option<HeaderKey>, pub bitpay: Option<HeaderKey>, pub bluesnap: Option<BodyKey>, pub boku: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 6dfd921a251..9a9a7606ca1 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -71,6 +71,7 @@ applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +billwerk.base_url = "https://api.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" @@ -142,6 +143,7 @@ cards = [ "authorizedotnet", "bambora", "bankofamerica", + "billwerk", "bitpay", "bluesnap", "boku", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 2be49d123b0..9098be40e21 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 airwallex applepay authorizedotnet bambora bankofamerica bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay "$1") + connectors=(aci adyen airwallex applepay authorizedotnet bambora bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2024-03-19T05:51:33Z
## 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 Billwerk Template connector code https://reference.reepay.com/api/ ### 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). --> #3227 ## 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)? --> Template code added hence no testing required ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
027080683d00a616e6dec40f57a4586951d76b09
juspay/hyperswitch
juspay__hyperswitch-3099
Bug: [FEATURE] Make PM auth service generic across Payment Method types ### Feature Description Currently, PM auth only supports ACH, need to make it generic across SEPA, BACS as well. ### Possible Implementation Will probably need some kind of parent structure to differentiate between types ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 35193b958f2..9873f62bfe1 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -222,17 +222,24 @@ pub struct PaymentMethodDataBankCreds { pub connector_details: Vec<BankAccountConnectorDetails>, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct BankAccountTokenData { + pub payment_method_type: api_enums::PaymentMethodType, + pub payment_method: api_enums::PaymentMethod, + pub connector_details: BankAccountConnectorDetails, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct BankAccountConnectorDetails { pub connector: String, - pub account_id: String, + pub account_id: masking::Secret<String>, pub mca_id: String, pub access_token: BankAccountAccessCreds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub enum BankAccountAccessCreds { - AccessToken(String), + AccessToken(masking::Secret<String>), } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs index 5e1ad67aead..f163875958e 100644 --- a/crates/pm_auth/src/connector/plaid/transformers.rs +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; -use common_enums::PaymentMethodType; -use masking::Secret; +use common_enums::{PaymentMethod, PaymentMethodType}; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{core::errors, types}; @@ -200,13 +200,19 @@ pub struct PlaidBankAccountCredentialsBacs { impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> { + let options = item.request.optional_ids.as_ref().map(|bank_account_ids| { + let ids = bank_account_ids + .ids + .iter() + .map(|id| id.peek().to_string()) + .collect::<Vec<_>>(); + + BankAccountCredentialsOptions { account_ids: ids } + }); + Ok(Self { - access_token: item.request.access_token.clone(), - options: item.request.optional_ids.as_ref().map(|bank_account_ids| { - BankAccountCredentialsOptions { - account_ids: bank_account_ids.ids.clone(), - } - }), + access_token: item.request.access_token.peek().to_string(), + options, }) } } @@ -232,26 +238,84 @@ impl<F, T> ) -> Result<Self, Self::Error> { let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts); let mut bank_account_vec = Vec::new(); - let mut id_to_suptype = HashMap::new(); + let mut id_to_subtype = HashMap::new(); accounts_info.into_iter().for_each(|acc| { - id_to_suptype.insert(acc.account_id, (acc.subtype, acc.name)); + id_to_subtype.insert(acc.account_id, (acc.subtype, acc.name)); }); account_numbers.ach.into_iter().for_each(|ach| { let (acc_type, acc_name) = - if let Some((_type, name)) = id_to_suptype.get(&ach.account_id) { + if let Some((_type, name)) = id_to_subtype.get(&ach.account_id) { (_type.to_owned(), Some(name.clone())) } else { (None, None) }; + let account_details = + types::PaymentMethodTypeDetails::Ach(types::BankAccountDetailsAch { + account_number: Secret::new(ach.account), + routing_number: Secret::new(ach.routing), + }); + let bank_details_new = types::BankAccountDetails { account_name: acc_name, - account_number: ach.account, - routing_number: ach.routing, + account_details, payment_method_type: PaymentMethodType::Ach, - account_id: ach.account_id, + payment_method: PaymentMethod::BankDebit, + account_id: ach.account_id.into(), + account_type: acc_type, + }; + + bank_account_vec.push(bank_details_new); + }); + + account_numbers.bacs.into_iter().for_each(|bacs| { + let (acc_type, acc_name) = + if let Some((_type, name)) = id_to_subtype.get(&bacs.account_id) { + (_type.to_owned(), Some(name.clone())) + } else { + (None, None) + }; + + let account_details = + types::PaymentMethodTypeDetails::Bacs(types::BankAccountDetailsBacs { + account_number: Secret::new(bacs.account), + sort_code: Secret::new(bacs.sort_code), + }); + + let bank_details_new = types::BankAccountDetails { + account_name: acc_name, + account_details, + payment_method_type: PaymentMethodType::Bacs, + payment_method: PaymentMethod::BankDebit, + account_id: bacs.account_id.into(), + account_type: acc_type, + }; + + bank_account_vec.push(bank_details_new); + }); + + account_numbers.international.into_iter().for_each(|sepa| { + let (acc_type, acc_name) = + if let Some((_type, name)) = id_to_subtype.get(&sepa.account_id) { + (_type.to_owned(), Some(name.clone())) + } else { + (None, None) + }; + + let account_details = + types::PaymentMethodTypeDetails::Sepa(types::BankAccountDetailsSepa { + iban: Secret::new(sepa.iban), + bic: Secret::new(sepa.bic), + }); + + let bank_details_new = types::BankAccountDetails { + account_name: acc_name, + account_details, + payment_method_type: PaymentMethodType::Sepa, + payment_method: PaymentMethod::BankDebit, + account_id: sepa.account_id.into(), account_type: acc_type, }; diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs index 6f5875247f1..51fd796072b 100644 --- a/crates/pm_auth/src/types.rs +++ b/crates/pm_auth/src/types.rs @@ -3,7 +3,7 @@ pub mod api; use std::marker::PhantomData; use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}; -use common_enums::PaymentMethodType; +use common_enums::{PaymentMethod, PaymentMethodType}; use masking::Secret; #[derive(Debug, Clone)] pub struct PaymentAuthRouterData<F, Request, Response> { @@ -55,13 +55,13 @@ pub type ExchangeTokenRouterData = #[derive(Debug, Clone)] pub struct BankAccountCredentialsRequest { - pub access_token: String, + pub access_token: Secret<String>, pub optional_ids: Option<BankAccountOptionalIDs>, } #[derive(Debug, Clone)] pub struct BankAccountOptionalIDs { - pub ids: Vec<String>, + pub ids: Vec<Secret<String>>, } #[derive(Debug, Clone)] @@ -72,13 +72,37 @@ pub struct BankAccountCredentialsResponse { #[derive(Debug, Clone)] pub struct BankAccountDetails { pub account_name: Option<String>, - pub account_number: String, - pub routing_number: String, + pub account_details: PaymentMethodTypeDetails, pub payment_method_type: PaymentMethodType, - pub account_id: String, + pub payment_method: PaymentMethod, + pub account_id: Secret<String>, pub account_type: Option<String>, } +#[derive(Debug, Clone)] +pub enum PaymentMethodTypeDetails { + Ach(BankAccountDetailsAch), + Bacs(BankAccountDetailsBacs), + Sepa(BankAccountDetailsSepa), +} +#[derive(Debug, Clone)] +pub struct BankAccountDetailsAch { + pub account_number: Secret<String>, + pub routing_number: Secret<String>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountDetailsBacs { + pub account_number: Secret<String>, + pub sort_code: Secret<String>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountDetailsSepa { + pub iban: Secret<String>, + pub bic: Secret<String>, +} + pub type BankDetailsRouterData = PaymentAuthRouterData< BankAccountCredentials, BankAccountCredentialsRequest, diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index f9d98647d1b..7ade016856c 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -6453,7 +6453,15 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::new(), + common: HashMap::from([ ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + )]), })] )} ), @@ -6466,7 +6474,15 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::new(), + common: HashMap::from([ ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + )]), } ), ]), @@ -6481,7 +6497,15 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::new(), + common: HashMap::from([ ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + )]), } ), ]), diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 60abf0701a5..41efea14942 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -7,7 +7,7 @@ use api_models::{ admin::{self, PaymentMethodsEnabled}, enums::{self as api_enums}, payment_methods::{ - BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, + BankAccountTokenData, CardDetailsPaymentMethod, CardNetworkTypes, CustomerDefaultPaymentMethodResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, @@ -2824,14 +2824,14 @@ pub async fn list_customer_payment_method( enums::PaymentMethod::BankDebit => { // Retrieve the pm_auth connector details so that it can be tokenized - let bank_account_connector_details = get_bank_account_connector_details(&pm, key) + let bank_account_token_data = get_bank_account_connector_details(&pm, key) .await .unwrap_or_else(|err| { logger::error!(error=?err); None }); - if let Some(connector_details) = bank_account_connector_details { - let token_data = PaymentTokenData::AuthBankDebit(connector_details); + if let Some(data) = bank_account_token_data { + let token_data = PaymentTokenData::AuthBankDebit(data); (None, None, token_data) } else { continue; @@ -3133,7 +3133,7 @@ async fn get_masked_bank_details( async fn get_bank_account_connector_details( pm: &payment_method::PaymentMethod, key: &[u8], -) -> errors::RouterResult<Option<BankAccountConnectorDetails>> { +) -> errors::RouterResult<Option<BankAccountTokenData>> { let payment_method_data = decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) .await @@ -3162,12 +3162,19 @@ async fn get_bank_account_connector_details( .connector_details .first() .ok_or(errors::ApiErrorResponse::InternalServerError)?; - Ok(Some(BankAccountConnectorDetails { - connector: connector_details.connector.clone(), - account_id: connector_details.account_id.clone(), - mca_id: connector_details.mca_id.clone(), - access_token: connector_details.access_token.clone(), - })) + + let pm_type = pm + .payment_method_type + .get_required_value("payment_method_type") + .attach_printable("PaymentMethodType not found")?; + + let token_data = BankAccountTokenData { + payment_method_type: pm_type, + payment_method: pm.payment_method, + connector_details: connector_details.clone(), + }; + + Ok(Some(token_data)) } }, None => Ok(None), diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 21ba27eac17..20db03a26a6 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -5,6 +5,7 @@ use api_models::{ payment_methods::{self, BankAccountAccessCreds}, payments::{AddressDetails, BankDebitBilling, BankDebitData, PaymentMethodData}, }; +use common_enums::PaymentMethodType; use hex; pub mod helpers; pub mod transformers; @@ -18,7 +19,7 @@ use common_utils::{ use data_models::payments::PaymentIntent; use error_stack::{IntoReport, ResultExt}; use helpers::PaymentAuthConnectorDataExt; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::{ connector::plaid::transformers::PlaidAuthType, types::{ @@ -273,7 +274,7 @@ async fn store_bank_details_in_payment_methods( merchant_account: domain::MerchantAccount, state: AppState, bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse, - connector_details: (&str, String), + connector_details: (&str, Secret<String>), mca_id: String, ) -> RouterResult<()> { let key = key_store.key.get_inner().peek(); @@ -357,7 +358,31 @@ async fn store_bank_details_in_payment_methods( let mut new_entries: Vec<storage::PaymentMethodNew> = Vec::new(); for creds in bank_account_details_resp.credentials { - let hash_string = format!("{}-{}", creds.account_number, creds.routing_number); + let (account_number, hash_string) = match creds.account_details { + pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => ( + ach.account_number.clone(), + format!( + "{}-{}-{}", + ach.account_number.peek(), + ach.routing_number.peek(), + PaymentMethodType::Ach, + ), + ), + pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => ( + bacs.account_number.clone(), + format!( + "{}-{}-{}", + bacs.account_number.peek(), + bacs.sort_code.peek(), + PaymentMethodType::Bacs + ), + ), + pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => ( + sepa.iban.clone(), + format!("{}-{}", sepa.iban.expose(), PaymentMethodType::Sepa), + ), + }; + let generated_hash = hex::encode( HmacSha256::sign_message(&HmacSha256, pm_auth_key.as_bytes(), hash_string.as_bytes()) .change_context(ApiErrorResponse::InternalServerError) @@ -366,8 +391,8 @@ async fn store_bank_details_in_payment_methods( let contains_account = hash_to_payment_method.get(&generated_hash); let mut pmd = payment_methods::PaymentMethodDataBankCreds { - mask: creds - .account_number + mask: account_number + .peek() .chars() .rev() .take(4) @@ -472,10 +497,10 @@ pub async fn get_bank_account_creds( connector: PaymentAuthConnectorData, merchant_account: &domain::MerchantAccount, connector_name: &str, - access_token: &str, + access_token: &Secret<String>, auth_type: pm_auth_types::ConnectorAuthType, state: &AppState, - bank_account_id: Option<String>, + bank_account_id: Option<Secret<String>>, ) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> { let connector_integration_bank_details: BoxedConnectorIntegration< '_, @@ -489,7 +514,7 @@ pub async fn get_bank_account_creds( merchant_id: Some(merchant_account.merchant_id.clone()), connector: Some(connector_name.to_string()), request: pm_auth_types::BankAccountCredentialsRequest { - access_token: access_token.to_string(), + access_token: access_token.clone(), optional_ids: bank_account_id .map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }), }, @@ -530,7 +555,7 @@ async fn get_access_token_from_exchange_api( payload: &api_models::pm_auth::ExchangeTokenCreateRequest, auth_type: &pm_auth_types::ConnectorAuthType, state: &AppState, -) -> RouterResult<String> { +) -> RouterResult<Secret<String>> { let connector_integration: BoxedConnectorIntegration< '_, ExchangeToken, @@ -573,7 +598,7 @@ async fn get_access_token_from_exchange_api( })?; let access_token = exchange_token_resp.access_token; - Ok(access_token) + Ok(Secret::new(access_token)) } async fn get_selected_config_from_redis( @@ -593,7 +618,9 @@ async fn get_selected_config_from_redis( "Vec<PaymentMethodAuthConnectorChoice>", ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment method auth connector name not found".to_string(), + }) .attach_printable("Failed to get payment method auth choices from redis")?; let selected_config = pm_auth_configs @@ -603,7 +630,7 @@ async fn get_selected_config_from_redis( && conf.payment_method_type == payload.payment_method_type }) .ok_or(ApiErrorResponse::GenericNotFoundError { - message: "connector name not found".to_string(), + message: "payment method auth connector name not found".to_string(), }) .into_report()? .clone(); @@ -614,14 +641,14 @@ async fn get_selected_config_from_redis( pub async fn retrieve_payment_method_from_auth_service( state: &AppState, key_store: &domain::MerchantKeyStore, - auth_token: &payment_methods::BankAccountConnectorDetails, + auth_token: &payment_methods::BankAccountTokenData, payment_intent: &PaymentIntent, customer: &Option<domain::Customer>, ) -> RouterResult<Option<(PaymentMethodData, enums::PaymentMethod)>> { let db = state.store.as_ref(); let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( - auth_token.connector.as_str(), + auth_token.connector_details.connector.as_str(), )?; let merchant_account = db @@ -632,12 +659,12 @@ pub async fn retrieve_payment_method_from_auth_service( let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &payment_intent.merchant_id, - &auth_token.mca_id, + &auth_token.connector_details.mca_id, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { - id: auth_token.mca_id.clone(), + id: auth_token.connector_details.mca_id.clone(), }) .attach_printable( "error while fetching merchant_connector_account from merchant_id and connector name", @@ -645,24 +672,27 @@ pub async fn retrieve_payment_method_from_auth_service( let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?; - let BankAccountAccessCreds::AccessToken(access_token) = &auth_token.access_token; + let BankAccountAccessCreds::AccessToken(access_token) = + &auth_token.connector_details.access_token; let bank_account_creds = get_bank_account_creds( connector, &merchant_account, - &auth_token.connector, + &auth_token.connector_details.connector, access_token, auth_type, state, - Some(auth_token.account_id.clone()), + Some(auth_token.connector_details.account_id.clone()), ) .await?; - logger::debug!("bank_creds: {:?}", bank_account_creds); - let bank_account = bank_account_creds .credentials - .first() + .iter() + .find(|acc| { + acc.payment_method_type == auth_token.payment_method_type + && acc.payment_method == auth_token.payment_method + }) .ok_or(errors::ApiErrorResponse::InternalServerError) .into_report() .attach_printable("Bank account details not found")?; @@ -686,7 +716,12 @@ pub async fn retrieve_payment_method_from_auth_service( let name = address .as_ref() - .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner())); + .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner())) + .ok_or(errors::ApiErrorResponse::GenericNotFoundError { + message: "billing_first_name not found".to_string(), + }) + .into_report() + .attach_printable("billing_first_name not found")?; let address_details = address.clone().map(|addr| { let line1 = addr.line1.map(|line1| line1.into_inner()); @@ -716,20 +751,41 @@ pub async fn retrieve_payment_method_from_auth_service( .map(common_utils::pii::Email::from) .get_required_value("email")?; - let payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { - billing_details: BankDebitBilling { - name: name.unwrap_or_default(), - email, - address: address_details, - }, - account_number: masking::Secret::new(bank_account.account_number.clone()), - routing_number: masking::Secret::new(bank_account.routing_number.clone()), - card_holder_name: None, - bank_account_holder_name: None, - bank_name: None, - bank_type, - bank_holder_type: None, - }); + let billing_details = BankDebitBilling { + name, + email, + address: address_details, + }; + + let payment_method_data = match &bank_account.account_details { + pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => { + PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { + billing_details, + account_number: ach.account_number.clone(), + routing_number: ach.routing_number.clone(), + card_holder_name: None, + bank_account_holder_name: None, + bank_name: None, + bank_type, + bank_holder_type: None, + }) + } + pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => { + PaymentMethodData::BankDebit(BankDebitData::BacsBankDebit { + billing_details, + account_number: bacs.account_number.clone(), + sort_code: bacs.sort_code.clone(), + bank_account_holder_name: None, + }) + } + pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => { + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { + billing_details, + iban: sepa.iban.clone(), + bank_account_holder_name: None, + }) + } + }; Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit))) } diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index d3339b7c4be..e1d74c70089 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -52,7 +52,7 @@ pub enum PaymentTokenData { TemporaryGeneric(GenericTokenData), Permanent(CardTokenData), PermanentCard(CardTokenData), - AuthBankDebit(payment_methods::BankAccountConnectorDetails), + AuthBankDebit(payment_methods::BankAccountTokenData), WalletToken(WalletTokenData), }
2023-12-12T10:21:17Z
## 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 --> Support for SEPA and BACS in direct debit PM auth. Earlier we only supported ACH based response from pm auth connector in PM auth, now have added support for BACS and SEPA based responses as well. ### 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)? --> Have tested locally by hardcoding response from connector. This cannot be tested as it is in sandbox because Plaid always sends a basic ACH based response in sandbox which won't trigger the response structure for BACS and SEPA (the implementation of this PR). A simple sanity testing however can be done for the feature, refer to this for testing instructions - https://github.com/juspay/hyperswitch/pull/3047 <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/2ec82cb1-8a1e-4d6f-b4ad-913bc082db54"> <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/aafcaa7a-fdca-4344-9ed1-8d3e19b91006"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1e32c6e873711e4f7715176c7d1057c18d4ec540
juspay/hyperswitch
juspay__hyperswitch-3089
Bug: [BUG] Payment Methods List filters not conscious of zero amount setup mandate payments ### Bug Description When a payment method is enabled for a particular connector with a minimum amount of `> 0`, and a zero amount setup mandate payment intent is created, the payment method doesn't show up in the list payment methods call even though amount constraints are not eligible for setup mandate payments. ### Expected Behavior The filters for list payment methods should skip amount checks if the payment is a setup mandate payment. ### Actual Behavior The amount constraints are applied to the merchant's payment methods which cause them to not show up in the response of the list payment methods call. ### Steps To Reproduce 1. Create a Merchant Account with 1 Merchant Connector account and give minimum amount as zero for all enabled payment methods 2. Create a payment with amount = 0, confirm = false & no payment method given 3. Do a list payment methods call for the created payment intent ### Context For The Bug - ### Environment - ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 84aef952a53..aaecd86627c 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2237,7 +2237,7 @@ fn filter_amount_based(payment_method: &RequestPaymentMethodTypes, amount: Optio // (Some(amt), Some(max_amt)) => amt <= max_amt, // (_, _) => true, // }; - min_check && max_check + (min_check && max_check) || amount == Some(0) } fn filter_pm_based_on_allowed_types( @@ -2296,8 +2296,9 @@ fn filter_payment_amount_based( pm: &RequestPaymentMethodTypes, ) -> bool { let amount = payment_intent.amount; - pm.maximum_amount.map_or(true, |amt| amount < amt.into()) - && pm.minimum_amount.map_or(true, |amt| amount > amt.into()) + (pm.maximum_amount.map_or(true, |amt| amount <= amt.into()) + && pm.minimum_amount.map_or(true, |amt| amount >= amt.into())) + || payment_intent.amount == 0 } async fn filter_payment_mandate_based(
2023-12-08T06:31:09Z
## 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 PR updates the List Payment Method core filters to allow payment intents with zero amount ### 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). --> Payment intents with zero amount are created for setting up a mandate with the connector and thus are a valid form of connector call. ## 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 Merchant Account, 1 Merchant Connector Account 2. Create a payment with amount = 0, confirm = false & no payment method given 3. Do a list payment methods call. The returned list should include all the eligible payment methods despite the amount being 0. <img width="551" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/577f1be7-e714-4951-97ea-2277ddebce6e"> <img width="551" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/bfc67914-ee7c-4fc9-adbb-0e00ab17ff2a"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
777cd5cdc2342fb7195a06505647fa331725e1dd
juspay/hyperswitch
juspay__hyperswitch-3175
Bug: [BUG] No provision for approving payments kept in ManualReview state for FRM flows ### Bug Description Once a fraudulent payment transaction is identified before authorization, it can be canceled or kept in manual reviewing state. If it is canceled, the payment is marked as a `failed` transaction. If the decision for the transaction is `manual_review`, it needs to be reviewed by the consumer and can be approved or rejected. If the transaction seem legit, the consumer can hit the `/approve` endpoint for approving the payments. This flow is broken. ### Expected Behavior If a txn is marked as `fraudulent`, it should still proceed for authorization, without capturing the amount. Upon approval, the amount can be captured. Upon rejection, the txn can be voided. ### Actual Behavior If a txn is marked as `fraudulent`, the flow would store the `payment_method_data` in locker, which could be later fetched if approval was given. Upon approval, it tries to fetch `payment_method_data` from locker, but fails (due to recent locker changes). Upon rejection, it marks the txn as `failed`. ### Steps To Reproduce 1. Create a merchant account 2. Create an API key 3. Add payment connector 4. Add FRM connector (enable pre flows for card, and set merchant_decision to `manual_review`) 5. Create a payment using debit / credit card w huge amounts, so it can be marked as fraudulent 6. Returned status - `requires_merchant_action` 7. Try to approve this payment 8. Returned error - payment_method_data not found ### Context For The Bug This is specifically for Pre-Transaction FRM flows, where the decision is set to `manual_review`. If a txn is stuck with state `requires_merchant_action`, those transactions can never be approved. They can only be rejected. ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `rustc 1.74.1 (a28077b28 2023-12-04)` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index ad3a7638774..0e3f67c051b 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -431,6 +431,7 @@ pub async fn pre_payment_frm_core<'a, F>( frm_configs: FrmConfigsObject, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, + should_continue_capture: &mut bool, key_store: domain::MerchantKeyStore, ) -> RouterResult<Option<FrmData>> where @@ -466,13 +467,12 @@ where .await?; let frm_fraud_check = frm_data_updated.fraud_check.clone(); payment_data.frm_message = Some(frm_fraud_check.clone()); - if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) - //DontTakeAction - { - *should_continue_transaction = false; + if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) { if matches!(frm_configs.frm_action, api_enums::FrmAction::CancelTxn) { + *should_continue_transaction = false; frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction); } else if matches!(frm_configs.frm_action, api_enums::FrmAction::ManualReview) { + *should_continue_capture = false; frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview); } } @@ -582,6 +582,7 @@ pub async fn call_frm_before_connector_call<'a, F, Req, Ctx>( frm_info: &mut Option<FrmInfo<F>>, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, + should_continue_capture: &mut bool, key_store: domain::MerchantKeyStore, ) -> RouterResult<Option<FrmConfigsObject>> where @@ -615,6 +616,7 @@ where frm_configs, customer, should_continue_transaction, + should_continue_capture, key_store, ) .await?; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 21cdec92ccb..5b6789dad0b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -181,6 +181,8 @@ where #[allow(unused_variables, unused_mut)] let mut should_continue_transaction: bool = true; #[cfg(feature = "frm")] + let mut should_continue_capture: bool = true; + #[cfg(feature = "frm")] let frm_configs = if state.conf.frm.enabled { frm_core::call_frm_before_connector_call( db, @@ -191,6 +193,7 @@ where &mut frm_info, &customer, &mut should_continue_transaction, + &mut should_continue_capture, key_store.clone(), ) .await? @@ -199,12 +202,25 @@ where }; #[cfg(feature = "frm")] logger::debug!( - "should_cancel_transaction: {:?} {:?} ", + "frm_configs: {:?}\nshould_cancel_transaction: {:?}\nshould_continue_capture: {:?}", frm_configs, - should_continue_transaction + should_continue_transaction, + should_continue_capture, ); if should_continue_transaction { + #[cfg(feature = "frm")] + match ( + should_continue_capture, + payment_data.payment_attempt.capture_method, + ) { + (false, Some(storage_enums::CaptureMethod::Automatic)) + | (false, Some(storage_enums::CaptureMethod::Scheduled)) => { + payment_data.payment_attempt.capture_method = + Some(storage_enums::CaptureMethod::Manual); + } + _ => (), + }; payment_data = match connector_details { api::ConnectorCallType::PreDetermined(connector) => { let schedule_time = if should_add_task_to_process_tracker { @@ -233,6 +249,10 @@ where &validate_result, schedule_time, header_payload, + #[cfg(feature = "frm")] + frm_info.as_ref().and_then(|fi| fi.suggested_action), + #[cfg(not(feature = "frm"))] + None, ) .await?; let operation = Box::new(PaymentResponse); @@ -284,6 +304,10 @@ where &validate_result, schedule_time, header_payload, + #[cfg(feature = "frm")] + frm_info.as_ref().and_then(|fi| fi.suggested_action), + #[cfg(not(feature = "frm"))] + None, ) .await?; @@ -311,6 +335,10 @@ where &customer, &validate_result, schedule_time, + #[cfg(feature = "frm")] + frm_info.as_ref().and_then(|fi| fi.suggested_action), + #[cfg(not(feature = "frm"))] + None, ) .await?; }; @@ -996,6 +1024,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>( validate_result: &operations::ValidateResult<'_>, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, + frm_suggestion: Option<storage_enums::FrmSuggestion>, ) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -1172,7 +1201,7 @@ where merchant_account.storage_scheme, updated_customer, key_store, - None, + frm_suggestion, header_payload, ) .await?; @@ -2109,6 +2138,7 @@ pub fn should_call_connector<Op: Debug, F: Clone>( } "CompleteAuthorize" => true, "PaymentApprove" => true, + "PaymentReject" => true, "PaymentSession" => true, "PaymentIncrementalAuthorization" => matches!( payment_data.payment_intent.status, diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index cddbc89acff..6d3697caabd 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -2,54 +2,51 @@ use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; -use data_models::mandates::MandateData; -use error_stack::{report, IntoReport, ResultExt}; +use error_stack::{IntoReport, ResultExt}; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ - errors::{self, CustomResult, RouterResult, StorageErrorExt}, + errors::{self, RouterResult, StorageErrorExt}, payment_methods::PaymentMethodRetrieve, - payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, + payments::{helpers, operations, PaymentAddress, PaymentData}, utils as core_utils, }, - db::StorageInterface, routes::AppState, services, types::{ - self, api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, - utils::{self, OptionExt}, + utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] -#[operation(operations = "all", flow = "authorize")] +#[operation(operations = "all", flow = "capture")] pub struct PaymentApprove; #[async_trait] impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> - GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentApprove + GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentApprove { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - request: &api::PaymentsRequest, - mandate_type: Option<api::MandateTransactionType>, + _request: &api::PaymentsCaptureRequest, + _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, - ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, Ctx>> { + ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, Ctx>> { let db = &*state.store; let merchant_id = &merchant_account.merchant_id; let storage_scheme = merchant_account.storage_scheme; - let (mut payment_intent, mut payment_attempt, currency, amount); + let (mut payment_intent, payment_attempt, currency, amount); let payment_id = payment_id .get_payment_intent_id() @@ -59,9 +56,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent.setup_future_usage = request - .setup_future_usage - .or(payment_intent.setup_future_usage); helpers::validate_payment_status_against_not_allowed_statuses( &payment_intent.status, @@ -69,7 +63,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, ], - "confirm", + "approve", )?; let profile_id = payment_intent @@ -87,31 +81,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> id: profile_id.to_string(), })?; - let ( - token, - payment_method, - payment_method_type, - setup_mandate, - recurring_mandate_payment_data, - mandate_connector, - ) = helpers::get_token_pm_type_mandate_details( - state, - request, - mandate_type.clone(), - merchant_account, - key_store, - ) - .await?; - - let browser_info = request - .browser_info - .clone() - .map(|x| utils::Encode::<types::BrowserInformation>::encode_to_value(&x)) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "browser_info", - })?; - let attempt_id = payment_intent.active_attempt.get_id().clone(); payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( @@ -123,35 +92,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let token = token.or_else(|| payment_attempt.payment_token.clone()); - - helpers::validate_pm_or_token_given( - &request.payment_method, - &request.payment_method_data, - &request.payment_method_type, - &mandate_type, - &token, - )?; - - payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); - payment_attempt.browser_info = browser_info; - payment_attempt.payment_method_type = - payment_method_type.or(payment_attempt.payment_method_type); - payment_attempt.payment_experience = request.payment_experience; currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); - helpers::validate_customer_id_mandatory_cases( - request.setup_future_usage.is_some(), - &payment_intent - .customer_id - .clone() - .or_else(|| request.customer_id.clone()), - )?; - let shipping_address = helpers::create_or_find_address_for_payment_by_request( db, - request.shipping.as_ref(), + None, payment_intent.shipping_address_id.as_deref(), merchant_id, payment_intent.customer_id.as_ref(), @@ -162,7 +108,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( db, - request.billing.as_ref(), + None, payment_intent.billing_address_id.as_deref(), merchant_id, payment_intent.customer_id.as_ref(), @@ -172,47 +118,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ) .await?; - let redirect_response = request - .feature_metadata - .as_ref() - .and_then(|fm| fm.redirect_response.clone()); - payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id); payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); - payment_intent.return_url = request - .return_url - .as_ref() - .map(|a| a.to_string()) - .or(payment_intent.return_url); - - payment_intent.allowed_payment_method_types = request - .get_allowed_payment_method_types_as_value() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error converting allowed_payment_types to Value")? - .or(payment_intent.allowed_payment_method_types); - - payment_intent.connector_metadata = request - .get_connector_metadata_as_value() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error converting connector_metadata to Value")? - .or(payment_intent.connector_metadata); - - payment_intent.feature_metadata = request - .get_feature_metadata_as_value() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error converting feature_metadata to Value")? - .or(payment_intent.feature_metadata); - - payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); - - // The operation merges mandate data from both request and payment_attempt - let setup_mandate = setup_mandate.map(|mandate_data| MandateData { - customer_acceptance: mandate_data.customer_acceptance, - mandate_type: payment_attempt - .mandate_details - .clone() - .or(mandate_data.mandate_type), - }); let frm_response = db .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.merchant_id.clone()) @@ -228,49 +135,41 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_attempt, currency, amount, - email: request.email.clone(), + email: None, mandate_id: None, - mandate_connector, - setup_mandate, - token, + mandate_connector: None, + setup_mandate: None, + token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), }, - confirm: request.confirm, - payment_method_data: request.payment_method_data.clone(), + confirm: None, + payment_method_data: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], - card_cvc: request.card_cvc.clone(), + card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, - recurring_mandate_payment_data, + recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, - redirect_response, + redirect_response: None, surcharge_details: None, frm_message: frm_response.ok(), payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], - frm_metadata: request.frm_metadata.clone(), + frm_metadata: None, }; - let customer_details = Some(CustomerDetails { - customer_id: request.customer_id.clone(), - name: request.name.clone(), - email: request.email.clone(), - phone: request.phone.clone(), - phone_country_code: request.phone_country_code.clone(), - }); - let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), - customer_details, + customer_details: None, payment_data, business_profile, }; @@ -279,91 +178,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> } } -#[async_trait] -impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx> - for PaymentApprove -{ - #[instrument(skip_all)] - async fn get_or_create_customer_details<'a>( - &'a self, - db: &dyn StorageInterface, - payment_data: &mut PaymentData<F>, - request: Option<CustomerDetails>, - key_store: &domain::MerchantKeyStore, - ) -> CustomResult< - ( - BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, - Option<domain::Customer>, - ), - errors::StorageError, - > { - helpers::create_customer_if_not_exist( - Box::new(self), - db, - payment_data, - request, - &key_store.merchant_id, - key_store, - ) - .await - } - - #[instrument(skip_all)] - async fn make_pm_data<'a>( - &'a self, - state: &'a AppState, - payment_data: &mut PaymentData<F>, - _storage_scheme: storage_enums::MerchantStorageScheme, - merchant_key_store: &domain::MerchantKeyStore, - customer: &Option<domain::Customer>, - ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, - Option<api::PaymentMethodData>, - )> { - let (op, payment_method_data) = helpers::make_pm_data( - Box::new(self), - state, - payment_data, - merchant_key_store, - customer, - ) - .await?; - - utils::when(payment_method_data.is_none(), || { - Err(errors::ApiErrorResponse::PaymentMethodNotFound) - })?; - - Ok((op, payment_method_data)) - } - - #[instrument(skip_all)] - async fn add_task_to_process_tracker<'a>( - &'a self, - _state: &'a AppState, - _payment_attempt: &storage::PaymentAttempt, - _requeue: bool, - _schedule_time: Option<time::PrimitiveDateTime>, - ) -> CustomResult<(), errors::ApiErrorResponse> { - Ok(()) - } - - async fn get_connector<'a>( - &'a self, - _merchant_account: &domain::MerchantAccount, - state: &AppState, - request: &api::PaymentsRequest, - _payment_intent: &storage::PaymentIntent, - _key_store: &domain::MerchantKeyStore, - ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { - // Use a new connector in the confirm call or use the same one which was passed when - // creating the payment or if none is passed then use the routing algorithm - helpers::get_connector_default(state, request.routing.clone()).await - } -} - #[async_trait] impl<F: Clone, Ctx: PaymentMethodRetrieve> - UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentApprove + UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentApprove { #[instrument(skip_all)] async fn update_trackers<'b>( @@ -377,7 +194,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>, PaymentData<F>, )> where @@ -401,16 +218,16 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> } } -impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx> - for PaymentApprove +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + ValidateRequest<F, api::PaymentsCaptureRequest, Ctx> for PaymentApprove { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, - request: &api::PaymentsRequest, + request: &api::PaymentsCaptureRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>, operations::ValidateResult<'a>, )> { let request_merchant_id = request.merchant_id.as_deref(); @@ -420,28 +237,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen expected_format: "merchant_id from merchant account".to_string(), })?; - helpers::validate_payment_method_fields_present(request)?; - - let mandate_type = - helpers::validate_mandate(request, payments::is_operation_confirm(self))?; - let payment_id = request - .payment_id - .clone() - .ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?; - Ok(( Box::new(self), operations::ValidateResult { merchant_id: &merchant_account.merchant_id, - payment_id: payment_id - .and_then(|id| core_utils::validate_id(id, "payment_id")) - .into_report()?, - mandate_type, - storage_scheme: merchant_account.storage_scheme, - requeue: matches!( - request.retry_action, - Some(api_models::enums::RetryAction::Requeue) + payment_id: api::PaymentIdType::PaymentIntentId( + core_utils::validate_id(request.payment_id.clone(), "payment_id") + .into_report()?, ), + mandate_type: None, + storage_scheme: merchant_account.storage_scheme, + requeue: false, }, )) } diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 37c7dfd1bae..e958422d312 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -1,6 +1,6 @@ use std::marker::PhantomData; -use api_models::{enums::FrmSuggestion, payments::PaymentsRejectRequest}; +use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; @@ -24,24 +24,24 @@ use crate::{ }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] -#[operation(operations = "all", flow = "reject")] +#[operation(operations = "all", flow = "cancel")] pub struct PaymentReject; #[async_trait] impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> - GetTracker<F, PaymentData<F>, PaymentsRejectRequest, Ctx> for PaymentReject + GetTracker<F, PaymentData<F>, PaymentsCancelRequest, Ctx> for PaymentReject { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - _request: &PaymentsRejectRequest, + _request: &PaymentsCancelRequest, _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, - ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsRejectRequest, Ctx>> { + ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, Ctx>> { let db = &*state.store; let merchant_id = &merchant_account.merchant_id; let storage_scheme = merchant_account.storage_scheme; @@ -57,6 +57,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> helpers::validate_payment_status_against_not_allowed_statuses( &payment_intent.status, &[ + enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, enums::IntentStatus::Processing, @@ -176,7 +177,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> #[async_trait] impl<F: Clone, Ctx: PaymentMethodRetrieve> - UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest, Ctx> for PaymentReject + UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest, Ctx> for PaymentReject { #[instrument(skip_all)] async fn update_trackers<'b>( @@ -190,7 +191,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> _should_decline_transaction: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, PaymentsRejectRequest, Ctx>, + BoxedOperation<'b, F, PaymentsCancelRequest, Ctx>, PaymentData<F>, )> where @@ -242,16 +243,16 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> } } -impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, PaymentsRejectRequest, Ctx> +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, PaymentsCancelRequest, Ctx> for PaymentReject { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, - request: &PaymentsRejectRequest, + request: &PaymentsCancelRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, PaymentsRejectRequest, Ctx>, + BoxedOperation<'b, F, PaymentsCancelRequest, Ctx>, operations::ValidateResult<'a>, )> { Ok(( diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 9ab0b4f817f..e5552f0d156 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -512,113 +512,132 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( }; (capture_update, attempt_update) } - Ok(payments_response) => match payments_response { - types::PaymentsResponseData::PreProcessingResponse { - pre_processing_id, - connector_metadata, - connector_response_reference_id, - .. - } => { - let connector_transaction_id = match pre_processing_id.to_owned() { - types::PreprocessingResponseId::PreProcessingId(_) => None, - types::PreprocessingResponseId::ConnectorTransactionId(connector_txn_id) => { - Some(connector_txn_id) - } - }; - let preprocessing_step_id = match pre_processing_id { - types::PreprocessingResponseId::PreProcessingId(pre_processing_id) => { - Some(pre_processing_id) + Ok(payments_response) => { + let attempt_status = payment_data.payment_attempt.status.to_owned(); + let connector_status = router_data.status.to_owned(); + let updated_attempt_status = match ( + connector_status, + attempt_status, + payment_data.frm_message.to_owned(), + ) { + ( + enums::AttemptStatus::Authorized, + enums::AttemptStatus::Unresolved, + Some(frm_message), + ) => match frm_message.frm_status { + enums::FraudCheckStatus::Fraud | enums::FraudCheckStatus::ManualReview => { + attempt_status } - types::PreprocessingResponseId::ConnectorTransactionId(_) => None, - }; - let payment_attempt_update = storage::PaymentAttemptUpdate::PreprocessingUpdate { - status: router_data.get_attempt_status_for_db_update(&payment_data), - payment_method_id: Some(router_data.payment_method_id), + _ => router_data.get_attempt_status_for_db_update(&payment_data), + }, + _ => router_data.get_attempt_status_for_db_update(&payment_data), + }; + match payments_response { + types::PaymentsResponseData::PreProcessingResponse { + pre_processing_id, connector_metadata, - preprocessing_step_id, - connector_transaction_id, connector_response_reference_id, - updated_by: storage_scheme.to_string(), - }; - - (None, Some(payment_attempt_update)) - } - types::PaymentsResponseData::TransactionResponse { - resource_id, - redirection_data, - connector_metadata, - connector_response_reference_id, - incremental_authorization_allowed, - .. - } => { - payment_data - .payment_intent - .incremental_authorization_allowed = - core_utils::get_incremental_authorization_allowed_value( - incremental_authorization_allowed, - payment_data - .payment_intent - .request_incremental_authorization, - ); - let connector_transaction_id = match resource_id { - types::ResponseId::NoResponseId => None, - types::ResponseId::ConnectorTransactionId(id) - | types::ResponseId::EncodedData(id) => Some(id), - }; - - let encoded_data = payment_data.payment_attempt.encoded_data.clone(); - - let authentication_data = redirection_data - .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data)) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Could not parse the connector response")?; - - // incase of success, update error code and error message - let error_status = if router_data.status == enums::AttemptStatus::Charged { - Some(None) - } else { - None - }; + .. + } => { + let connector_transaction_id = match pre_processing_id.to_owned() { + types::PreprocessingResponseId::PreProcessingId(_) => None, + types::PreprocessingResponseId::ConnectorTransactionId( + connector_txn_id, + ) => Some(connector_txn_id), + }; + let preprocessing_step_id = match pre_processing_id { + types::PreprocessingResponseId::PreProcessingId(pre_processing_id) => { + Some(pre_processing_id) + } + types::PreprocessingResponseId::ConnectorTransactionId(_) => None, + }; + let payment_attempt_update = + storage::PaymentAttemptUpdate::PreprocessingUpdate { + status: updated_attempt_status, + payment_method_id: Some(router_data.payment_method_id), + connector_metadata, + preprocessing_step_id, + connector_transaction_id, + connector_response_reference_id, + updated_by: storage_scheme.to_string(), + }; - if router_data.status == enums::AttemptStatus::Charged { - metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]); + (None, Some(payment_attempt_update)) } + types::PaymentsResponseData::TransactionResponse { + resource_id, + redirection_data, + connector_metadata, + connector_response_reference_id, + incremental_authorization_allowed, + .. + } => { + payment_data + .payment_intent + .incremental_authorization_allowed = + core_utils::get_incremental_authorization_allowed_value( + incremental_authorization_allowed, + payment_data + .payment_intent + .request_incremental_authorization, + ); + let connector_transaction_id = match resource_id { + types::ResponseId::NoResponseId => None, + types::ResponseId::ConnectorTransactionId(id) + | types::ResponseId::EncodedData(id) => Some(id), + }; - utils::add_apple_pay_payment_status_metrics( - router_data.status, - router_data.apple_pay_flow.clone(), - payment_data.payment_attempt.connector.clone(), - payment_data.payment_attempt.merchant_id.clone(), - ); + let encoded_data = payment_data.payment_attempt.encoded_data.clone(); - let (capture_updates, payment_attempt_update) = match payment_data - .multiple_capture_data - { - Some(multiple_capture_data) => { - let capture_update = storage::CaptureUpdate::ResponseUpdate { - status: enums::CaptureStatus::foreign_try_from(router_data.status)?, - connector_capture_id: connector_transaction_id.clone(), - connector_response_reference_id, - }; - let capture_update_list = vec![( - multiple_capture_data.get_latest_capture().clone(), - capture_update, - )]; - (Some((multiple_capture_data, capture_update_list)), None) + let authentication_data = redirection_data + .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data)) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not parse the connector response")?; + + // incase of success, update error code and error message + let error_status = if router_data.status == enums::AttemptStatus::Charged { + Some(None) + } else { + None + }; + + if router_data.status == enums::AttemptStatus::Charged { + metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]); } - None => { - let status = router_data.get_attempt_status_for_db_update(&payment_data); - ( + + utils::add_apple_pay_payment_status_metrics( + router_data.status, + router_data.apple_pay_flow.clone(), + payment_data.payment_attempt.connector.clone(), + payment_data.payment_attempt.merchant_id.clone(), + ); + + let (capture_updates, payment_attempt_update) = match payment_data + .multiple_capture_data + { + Some(multiple_capture_data) => { + let capture_update = storage::CaptureUpdate::ResponseUpdate { + status: enums::CaptureStatus::foreign_try_from(router_data.status)?, + connector_capture_id: connector_transaction_id.clone(), + connector_response_reference_id, + }; + let capture_update_list = vec![( + multiple_capture_data.get_latest_capture().clone(), + capture_update, + )]; + (Some((multiple_capture_data, capture_update_list)), None) + } + None => ( None, Some(storage::PaymentAttemptUpdate::ResponseUpdate { - status, + status: updated_attempt_status, connector: None, connector_transaction_id: connector_transaction_id.clone(), authentication_type: None, amount_capturable: router_data .request - .get_amount_capturable(&payment_data, status), + .get_amount_capturable(&payment_data, updated_attempt_status), payment_method_id: Some(router_data.payment_method_id), mandate_id: payment_data .mandate_id @@ -636,56 +655,58 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( authentication_data, encoded_data, }), - ) - } - }; + ), + }; - (capture_updates, payment_attempt_update) - } - types::PaymentsResponseData::TransactionUnresolvedResponse { - resource_id, - reason, - connector_response_reference_id, - } => { - let connector_transaction_id = match resource_id { - types::ResponseId::NoResponseId => None, - types::ResponseId::ConnectorTransactionId(id) - | types::ResponseId::EncodedData(id) => Some(id), - }; - ( - None, - Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate { - status: router_data.get_attempt_status_for_db_update(&payment_data), - connector: None, - connector_transaction_id, - payment_method_id: Some(router_data.payment_method_id), - error_code: Some(reason.clone().map(|cd| cd.code)), - error_message: Some(reason.clone().map(|cd| cd.message)), - error_reason: Some(reason.map(|cd| cd.message)), - connector_response_reference_id, - updated_by: storage_scheme.to_string(), - }), - ) - } - types::PaymentsResponseData::SessionResponse { .. } => (None, None), - types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None), - types::PaymentsResponseData::TokenizationResponse { .. } => (None, None), - types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None), - types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None), - types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => (None, None), - types::PaymentsResponseData::MultipleCaptureResponse { - capture_sync_response_list, - } => match payment_data.multiple_capture_data { - Some(multiple_capture_data) => { - let capture_update_list = response_to_capture_update( - &multiple_capture_data, - capture_sync_response_list, - )?; - (Some((multiple_capture_data, capture_update_list)), None) + (capture_updates, payment_attempt_update) } - None => (None, None), - }, - }, + types::PaymentsResponseData::TransactionUnresolvedResponse { + resource_id, + reason, + connector_response_reference_id, + } => { + let connector_transaction_id = match resource_id { + types::ResponseId::NoResponseId => None, + types::ResponseId::ConnectorTransactionId(id) + | types::ResponseId::EncodedData(id) => Some(id), + }; + ( + None, + Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate { + status: updated_attempt_status, + connector: None, + connector_transaction_id, + payment_method_id: Some(router_data.payment_method_id), + error_code: Some(reason.clone().map(|cd| cd.code)), + error_message: Some(reason.clone().map(|cd| cd.message)), + error_reason: Some(reason.map(|cd| cd.message)), + connector_response_reference_id, + updated_by: storage_scheme.to_string(), + }), + ) + } + types::PaymentsResponseData::SessionResponse { .. } => (None, None), + types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None), + types::PaymentsResponseData::TokenizationResponse { .. } => (None, None), + types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None), + types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None), + types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => { + (None, None) + } + types::PaymentsResponseData::MultipleCaptureResponse { + capture_sync_response_list, + } => match payment_data.multiple_capture_data { + Some(multiple_capture_data) => { + let capture_update_list = response_to_capture_update( + &multiple_capture_data, + capture_sync_response_list, + )?; + (Some((multiple_capture_data, capture_update_list)), None) + } + None => (None, None), + }, + } + } }; payment_data.multiple_capture_data = match capture_update { Some((mut multiple_capture_data, capture_updates)) => { diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 0fd45c5af3b..8d74eb3fa96 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -40,6 +40,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, Ctx>( customer: &Option<domain::Customer>, validate_result: &operations::ValidateResult<'_>, schedule_time: Option<time::PrimitiveDateTime>, + frm_suggestion: Option<storage_enums::FrmSuggestion>, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, @@ -90,6 +91,7 @@ where validate_result, schedule_time, true, + frm_suggestion, ) .await?; } @@ -133,6 +135,7 @@ where schedule_time, //this is an auto retry payment, but not step-up false, + frm_suggestion, ) .await?; @@ -275,6 +278,7 @@ pub async fn do_retry<F, ApiRequest, FData, Ctx>( validate_result: &operations::ValidateResult<'_>, schedule_time: Option<time::PrimitiveDateTime>, is_step_up: bool, + frm_suggestion: Option<storage_enums::FrmSuggestion>, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, @@ -310,6 +314,7 @@ where validate_result, schedule_time, api::HeaderPayload::default(), + frm_suggestion, ) .await } diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 34f41c49cdd..379cd4f2f1f 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -968,7 +968,7 @@ pub async fn payments_approve( payload.clone(), |state, auth, req| { payments::payments_core::< - api_types::Authorize, + api_types::Capture, payment_types::PaymentsResponse, _, _, @@ -979,10 +979,8 @@ pub async fn payments_approve( auth.merchant_account, auth.key_store, payments::PaymentApprove, - payment_types::PaymentsRequest { - payment_id: Some(payment_types::PaymentIdType::PaymentIntentId( - req.payment_id, - )), + payment_types::PaymentsCaptureRequest { + payment_id: req.payment_id, ..Default::default() }, api::AuthFlow::Merchant, @@ -1030,7 +1028,7 @@ pub async fn payments_reject( payload.clone(), |state, auth, req| { payments::payments_core::< - api_types::Reject, + api_types::Void, payment_types::PaymentsResponse, _, _, @@ -1041,7 +1039,11 @@ pub async fn payments_reject( auth.merchant_account, auth.key_store, payments::PaymentReject, - req, + payment_types::PaymentsCancelRequest { + payment_id: req.payment_id, + cancellation_reason: Some("Rejected by merchant".to_string()), + ..Default::default() + }, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None,
2023-12-20T09:15:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description #3175 ### 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? Tested locally using postman collection https://galactic-capsule-229427.postman.co/workspace/My-Workspace~2b563e0d-bad3-420f-8c0b-0fd5b278a4fe/collection/9906252-e8ad195c-90f5-4527-a40b-1a25bc9bedd2?action=share&creator=9906252 **Test Cases** - Payments <> FRM manual flow (pre + post) - Approve + Rejection should be working ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1bbd9d5df0f145f192d0271d89761488e7347989
juspay/hyperswitch
juspay__hyperswitch-3147
Bug: [REFACTOR] Handle card duplication ### Feature Description Currently card duplication and card metadata (card_holder_name, expiry year, expiry month, etc) changes are not being handled in Hyperswitch. ### Possible Implementation Rust locker sends `duplication_check` status in its store card response. Based on this response, duplication has to be handled ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 7b505e7c01c..dfbd9211dfb 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -109,7 +109,10 @@ pub fn store_default_payment_method( req: &api::PaymentMethodCreate, customer_id: &str, merchant_id: &String, -) -> (api::PaymentMethodResponse, bool) { +) -> ( + api::PaymentMethodResponse, + Option<payment_methods::DataDuplicationCheck>, +) { let pm_id = generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.to_string(), @@ -125,7 +128,7 @@ pub fn store_default_payment_method( installment_payment_enabled: false, //[#219] payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] }; - (payment_method_response, false) + (payment_method_response, None) } #[instrument(skip_all)] @@ -136,6 +139,7 @@ pub async fn add_payment_method( key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { req.validate()?; + let db = &*state.store; let merchant_id = &merchant_account.merchant_id; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; @@ -178,34 +182,179 @@ pub async fn add_payment_method( )), }; - let (resp, is_duplicate) = response?; - if !is_duplicate { - let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); + let (resp, duplication_check) = response?; + + match duplication_check { + Some(duplication_check) => match duplication_check { + payment_methods::DataDuplicationCheck::Duplicated => { + let existing_pm = db.find_payment_method(&resp.payment_method_id).await; + + if let Err(err) = existing_pm { + if err.current_context().is_db_not_found() { + insert_payment_method( + db, + &resp, + req, + key_store, + merchant_id, + &customer_id, + None, + ) + .await + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while finding payment method") + }? + }; + } - let pm_card_details = resp - .card - .as_ref() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + payment_methods::DataDuplicationCheck::MetaDataChanged => { + if let Some(card) = req.card.clone() { + delete_card_from_locker( + &state, + &customer_id, + merchant_id, + &resp.payment_method_id, + ) + .await?; + + let add_card_resp = add_card_hs( + &state, + req.clone(), + &card, + customer_id.clone(), + merchant_account, + api::enums::LockerChoice::Tartarus, + Some(&resp.payment_method_id), + ) + .await; - let pm_data_encrypted = - create_encrypted_payment_method_data(key_store, pm_card_details).await; + if let Err(err) = add_card_resp { + logger::error!(vault_err=?err); + db.delete_payment_method_by_merchant_id_payment_method_id( + merchant_id, + &resp.payment_method_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - create_payment_method( - &*state.store, - &req, - &customer_id, - &resp.payment_method_id, - &resp.merchant_id, - pm_metadata.cloned(), - pm_data_encrypted, - key_store, - ) - .await?; - } + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while updating card metadata changes"))? + }; + + let existing_pm = db.find_payment_method(&resp.payment_method_id).await; + match existing_pm { + Ok(pm) => { + let updated_card = Some(api::CardDetailFromLocker { + scheme: None, + last4_digits: Some( + card.card_number + .to_string() + .split_off(card.card_number.to_string().len() - 4), + ), + issuer_country: None, + card_number: Some(card.card_number), + expiry_month: Some(card.card_exp_month), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_network: None, + card_isin: None, + card_issuer: None, + card_type: None, + saved_to_locker: true, + }); + + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from( + card.clone(), + )) + }); + let pm_data_encrypted = + create_encrypted_payment_method_data(key_store, updated_pmd).await; + + let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: pm_data_encrypted, + }; + + db.update_payment_method(pm, pm_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; + } + Err(err) => { + if err.current_context().is_db_not_found() { + insert_payment_method( + db, + &resp, + req, + key_store, + merchant_id, + &customer_id, + None, + ) + .await + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while finding payment method") + }?; + } + } + } + } + }, + None => { + let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); + + insert_payment_method( + db, + &resp, + req, + key_store, + merchant_id, + &customer_id, + pm_metadata.cloned(), + ) + .await?; + } + }; Ok(services::ApplicationResponse::Json(resp)) } +pub async fn insert_payment_method( + db: &dyn db::StorageInterface, + resp: &api::PaymentMethodResponse, + req: api::PaymentMethodCreate, + key_store: &domain::MerchantKeyStore, + merchant_id: &str, + customer_id: &str, + pm_metadata: Option<serde_json::Value>, +) -> errors::RouterResult<()> { + let pm_card_details = resp + .card + .as_ref() + .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + let pm_data_encrypted = create_encrypted_payment_method_data(key_store, pm_card_details).await; + create_payment_method( + db, + &req, + customer_id, + &resp.payment_method_id, + merchant_id, + pm_metadata, + pm_data_encrypted, + key_store, + ) + .await?; + + Ok(()) +} + #[instrument(skip_all)] pub async fn update_customer_payment_method( state: routes::AppState, @@ -264,7 +413,13 @@ pub async fn add_bank_to_locker( key_store: &domain::MerchantKeyStore, bank: &api::BankPayout, customer_id: &String, -) -> errors::CustomResult<(api::PaymentMethodResponse, bool), errors::VaultError> { +) -> errors::CustomResult< + ( + api::PaymentMethodResponse, + Option<payment_methods::DataDuplicationCheck>, + ), + errors::VaultError, +> { let key = key_store.key.get_inner().peek(); let payout_method_data = api::PayoutMethodData::Bank(bank.clone()); let enc_data = async { @@ -312,7 +467,7 @@ pub async fn add_bank_to_locker( req, &merchant_account.merchant_id, ); - Ok((payment_method_resp, store_resp.duplicate.unwrap_or(false))) + Ok((payment_method_resp, store_resp.duplication_check)) } /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method @@ -322,7 +477,13 @@ pub async fn add_card_to_locker( card: &api::CardDetail, customer_id: &String, merchant_account: &domain::MerchantAccount, -) -> errors::CustomResult<(api::PaymentMethodResponse, bool), errors::VaultError> { +) -> errors::CustomResult< + ( + api::PaymentMethodResponse, + Option<payment_methods::DataDuplicationCheck>, + ), + errors::VaultError, +> { metrics::STORED_TO_LOCKER.add(&metrics::CONTEXT, 1, &[]); let add_card_to_hs_resp = request::record_operation_time( async { @@ -540,7 +701,13 @@ pub async fn add_card_hs( merchant_account: &domain::MerchantAccount, locker_choice: api_enums::LockerChoice, card_reference: Option<&str>, -) -> errors::CustomResult<(api::PaymentMethodResponse, bool), errors::VaultError> { +) -> errors::CustomResult< + ( + api::PaymentMethodResponse, + Option<payment_methods::DataDuplicationCheck>, + ), + errors::VaultError, +> { let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq { merchant_id: &merchant_account.merchant_id, merchant_customer_id: customer_id.to_owned(), @@ -565,11 +732,7 @@ pub async fn add_card_hs( req, &merchant_account.merchant_id, ); - - Ok(( - payment_method_resp, - store_card_payload.duplicate.unwrap_or(false), - )) + Ok((payment_method_resp, store_card_payload.duplication_check)) } #[instrument(skip_all)] @@ -875,7 +1038,7 @@ pub async fn mock_call_to_locker_hs<'a>( .change_context(errors::VaultError::SaveCardFailed)?; let payload = payment_methods::StoreCardRespPayload { card_reference: response.card_id, - duplicate: Some(false), + duplication_check: None, }; Ok(payment_methods::StoreCardResp { status: "SUCCESS".to_string(), diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 360efb7ddad..59b02d01933 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -62,7 +62,14 @@ pub struct StoreCardResp { #[derive(Debug, Deserialize, Serialize)] pub struct StoreCardRespPayload { pub card_reference: String, - pub duplicate: Option<bool>, + pub duplication_check: Option<DataDuplicationCheck>, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum DataDuplicationCheck { + Duplicated, + MetaDataChanged, } #[derive(Debug, Deserialize, Serialize)] diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 1b9f512d842..9691ea962fa 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,3 +1,4 @@ +use api_models::payment_methods::PaymentMethodsData; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; @@ -6,7 +7,7 @@ use router_env::{instrument, tracing}; use super::helpers; use crate::{ core::{ - errors::{self, ConnectorErrorExt, RouterResult}, + errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payment_methods, payments, }, logger, @@ -16,7 +17,7 @@ use crate::{ self, api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, - storage::enums as storage_enums, + storage::{self, enums as storage_enums}, }, utils::OptionExt, }; @@ -99,7 +100,7 @@ where .await? }; - let is_duplicate = locker_response.1; + let duplication_check = locker_response.1; let pm_card_details = locker_response.0.card.as_ref().map(|card| { api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from( @@ -114,29 +115,31 @@ where ) .await; - if is_duplicate { - let existing_pm = db - .find_payment_method(&locker_response.0.payment_method_id) - .await; - match existing_pm { - Ok(pm) => { - let pm_metadata = create_payment_method_metadata( - pm.metadata.as_ref(), - connector_token, - )?; - if let Some(metadata) = pm_metadata { - payment_methods::cards::update_payment_method(db, pm, metadata) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add payment method in db")?; - }; - } - Err(error) => { - match error.current_context() { - errors::StorageError::DatabaseError(err) => match err - .current_context() - { - diesel_models::errors::DatabaseError::NotFound => { + match duplication_check { + Some(duplication_check) => match duplication_check { + payment_methods::transformers::DataDuplicationCheck::Duplicated => { + let existing_pm = db + .find_payment_method(&locker_response.0.payment_method_id) + .await; + match existing_pm { + Ok(pm) => { + let pm_metadata = create_payment_method_metadata( + pm.metadata.as_ref(), + connector_token, + )?; + if let Some(metadata) = pm_metadata { + payment_methods::cards::update_payment_method( + db, pm, metadata, + ) + .await + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable("Failed to add payment method in db")?; + }; + } + Err(err) => { + if err.current_context().is_db_not_found() { let pm_metadata = create_payment_method_metadata(None, connector_token)?; payment_methods::cards::create_payment_method( @@ -150,33 +153,149 @@ where key_store, ) .await - } - _ => { - Err(report!(errors::ApiErrorResponse::InternalServerError) + } else { + Err(err) + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable("Error while finding payment method") + }?; + } + }; + } + payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => { + if let Some(card) = payment_method_create_request.card.clone() { + payment_methods::cards::delete_card_from_locker( + state, + &customer.customer_id, + merchant_id, + &locker_response.0.payment_method_id, + ) + .await?; + + let add_card_resp = payment_methods::cards::add_card_hs( + state, + payment_method_create_request.clone(), + &card, + customer.customer_id.clone(), + merchant_account, + api::enums::LockerChoice::Tartarus, + Some(&locker_response.0.payment_method_id), + ) + .await; + + if let Err(err) = add_card_resp { + logger::error!(vault_err=?err); + db.delete_payment_method_by_merchant_id_payment_method_id( + merchant_id, + &locker_response.0.payment_method_id, + ) + .await + .to_not_found_response( + errors::ApiErrorResponse::PaymentMethodNotFound, + )?; + + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed while updating card metadata changes", + ))? + }; + + let existing_pm = db + .find_payment_method(&locker_response.0.payment_method_id) + .await; + match existing_pm { + Ok(pm) => { + let updated_card = Some(CardDetailFromLocker { + scheme: None, + last4_digits: Some( + card.card_number.to_string().split_off( + card.card_number.to_string().len() - 4, + ), + ), + issuer_country: None, + card_number: Some(card.card_number), + expiry_month: Some(card.card_exp_month), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_network: None, + card_isin: None, + card_issuer: None, + card_type: None, + saved_to_locker: true, + }); + + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card( + CardDetailsPaymentMethod::from(card.clone()), + ) + }); + let pm_data_encrypted = + payment_methods::cards::create_encrypted_payment_method_data( + key_store, + updated_pmd, + ) + .await; + + let pm_update = + storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: pm_data_encrypted, + }; + + db.update_payment_method(pm, pm_update) + .await + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) .attach_printable( - "Database Error while finding payment method", - )) + "Failed to add payment method in db", + )?; + } + Err(err) => { + if err.current_context().is_db_not_found() { + payment_methods::cards::insert_payment_method( + db, + &locker_response.0, + payment_method_create_request, + key_store, + merchant_id, + &customer.customer_id, + None, + ) + .await + } else { + Err(err) + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable( + "Error while finding payment method", + ) + }?; } - }, - _ => Err(report!(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error while finding payment method")), - }?; + } + } } - }; - } else { - let pm_metadata = create_payment_method_metadata(None, connector_token)?; - payment_methods::cards::create_payment_method( - db, - &payment_method_create_request, - &customer.customer_id, - &locker_response.0.payment_method_id, - merchant_id, - pm_metadata, - pm_data_encrypted, - key_store, - ) - .await?; - }; + }, + None => { + let pm_metadata = create_payment_method_metadata(None, connector_token)?; + payment_methods::cards::create_payment_method( + db, + &payment_method_create_request, + &customer.customer_id, + &locker_response.0.payment_method_id, + merchant_id, + pm_metadata, + pm_data_encrypted, + key_store, + ) + .await?; + } + } + Some(locker_response.0.payment_method_id) } else { None @@ -190,7 +309,10 @@ where async fn skip_saving_card_in_locker( merchant_account: &domain::MerchantAccount, payment_method_request: api::PaymentMethodCreate, -) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { +) -> RouterResult<( + api_models::payment_methods::PaymentMethodResponse, + Option<payment_methods::transformers::DataDuplicationCheck>, +)> { let merchant_id = &merchant_account.merchant_id; let customer_id = payment_method_request .clone() @@ -243,7 +365,7 @@ async fn skip_saving_card_in_locker( bank_transfer: None, }; - Ok((pm_resp, false)) + Ok((pm_resp, None)) } None => { let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); @@ -261,7 +383,7 @@ async fn skip_saving_card_in_locker( payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), bank_transfer: None, }; - Ok((payment_method_response, false)) + Ok((payment_method_response, None)) } } } @@ -270,7 +392,10 @@ pub async fn save_in_locker( state: &AppState, merchant_account: &domain::MerchantAccount, payment_method_request: api::PaymentMethodCreate, -) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { +) -> RouterResult<( + api_models::payment_methods::PaymentMethodResponse, + Option<payment_methods::transformers::DataDuplicationCheck>, +)> { payment_method_request.validate()?; let merchant_id = &merchant_account.merchant_id; let customer_id = payment_method_request @@ -304,7 +429,7 @@ pub async fn save_in_locker( installment_payment_enabled: false, //[#219] payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] }; - Ok((payment_method_response, false)) + Ok((payment_method_response, None)) } } }
2023-12-15T14:56:35Z
## 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 card duplication and card metadata (card_holder_name, expiry year, expiry month, etc) changes are not being handled in Hyperswitch. Rust locker has the following changes made - a new field `duplication_check` has been added in stored card response. This field can have three values (duplicated, meta_data_changed and null). * `duplicated` : indicates that the entire card details in the card request is already present in the locker. * `meta_data_changed` : indicates that there is already a saved card with same card number but with different card details (like expiry or card holder name). * `null` : indicates that card is not present in the locker. This PR handles above response from locker in two different flows. * During `/payments` api call with `setup_future_usage = on_session` * During `/payment_methods` api call to add card directly Below are the ways in which Hyperswitch will behave based on above 3 values of `duplication_check` * `duplicated` : Since card already exist on locker, just ensure corresponding payment method entry is present in `payment_methods` table. If not we create it with the `payment_method_id` (locker_id) returned by locker. * `meta_data_changed` : Send a delete request to locker. Send a add card request to locker with the updated card details but same `payment_method_id` (This ensures that we don't re-create payment method entry on Hyperswitch side). Next update the `payment_method_data` field in `payment_methods` table to contain the new card details. * `null` : New payment method entry is created as this is a new card. ### 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 account, api key and stripe mca. This PR has to be tested in below 2 flows as these are the two ways in which we can send add card request to locker. i) Directly adding card using `/payment_methods` api ii) Using `/payments` api with `setup_future_usage = on_session` ## i) Directly adding card using `/payment_methods` api - 1. Create a `Customer` ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2csdyoNPcAqi4zqAg0oPDbCjQu4zoMzZ1JOrMDQ9zoe0CZ7rfrdI2r9Ju3o1M7ya' \ --data-raw '{ "email": "guest@example.com", "name": "David", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 2. Hit add card request with the `customer_id` from above request (Try some new test card which shouldn't exist in locker) ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2csdyoNPcAqi4zqAg0oPDbCjQu4zoMzZ1JOrMDQ9zoe0CZ7rfrdI2r9Ju3o1M7ya' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "4000002500001001", "card_exp_month": "01", "card_exp_year": "42", "card_holder_name": "Devid" }, "customer_id": "{{customer_id}}", "metadata": { "city": "NY", "unit": "245" } }' ``` Below is the locker response I logged for testing purpose - ``` StoreCardRespPayload { card_reference: "3e9223a0-6508-4957-b947-9b2b6f7189b0", duplication_check: None } ``` `duplication_check` says None. Also make sure payment method entry is created in hyperswitch side in using `list_customer_payment_method` api 3. Now try to hit the same add card request without any change in card params. Locker response - ``` StoreCardRespPayload { card_reference: "3e9223a0-6508-4957-b947-9b2b6f7189b0", duplication_check: Some(Duplicated) } ``` `duplication_check` says `Duplicated` which means whole card is found in locker without any change in card metadata (expiry year, expiry month, card holder name, etc) Make sure no new entry is created in `payment_methods` table as this was a duplicate card. Check this by again doing `list_customer_payment_method` and this should still have 1 card. 4. Now change the metadata of card (ex - card holder name) and make add card request. Locker response - ``` StoreCardRespPayload { card_reference: "3e9223a0-6508-4957-b947-9b2b6f7189b0", duplication_check: Some(MetaDataChanged) } ``` `duplication_check` says `MetaDataChanged` which means card was found but some of its metadata was changed. At this point the card details (metadata) must be updated as per request sent. Do `list_customer_payment_method` and this response should have the metadata changes you have done. ## ii) Using `/payments` api with `setup_future_usage = on_session` 1. Create a `Customer` ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2csdyoNPcAqi4zqAg0oPDbCjQu4zoMzZ1JOrMDQ9zoe0CZ7rfrdI2r9Ju3o1M7ya' \ --data-raw '{ "email": "guest@example.com", "name": "David", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 2. Hit `/payments` api with `setup_future_usage = on_session` with card thats not present in locker. Make sure to use above `customer_id` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2csdyoNPcAqi4zqAg0oPDbCjQu4zoMzZ1JOrMDQ9zoe0CZ7rfrdI2r9Ju3o1M7ya' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "{{customer_id}}", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4000002500001001", "card_exp_month": "12", "card_exp_year": "42", "card_holder_name": "David", "card_cvc": "900" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "business_label": "default", "business_country": "US" }' ``` This time card has to be saved in locker and `payment_methods` entry has to be created in hyperswitch. Verify by hitting `list_customer_payment_method`. 3. Now for the same customer try to make another payment without changing anything (same card). This time as this is a duplicate card, no new entry has to be created in `payment_methods` table. Verify by hitting `list_customer_payment_method` and this should still have 1 card. 4. Change some metadata and make a payment for same customer. 5. Do `list_customer_payment_method` and this response should have the metadata changes you have done. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3a869a2d5731a2393a687ed7773eda5344bd8e3f
juspay/hyperswitch
juspay__hyperswitch-3044
Bug: [FEATURE] Implement `AuthorizationInterface` for `MockDb` Spin off from https://github.com/juspay/hyperswitch/issues/172. Refer to the parent issue for more information
diff --git a/crates/diesel_models/src/authorization.rs b/crates/diesel_models/src/authorization.rs index 64fd1c65187..b6f75bbb9b7 100644 --- a/crates/diesel_models/src/authorization.rs +++ b/crates/diesel_models/src/authorization.rs @@ -57,6 +57,21 @@ pub struct AuthorizationUpdateInternal { pub connector_authorization_id: Option<String>, } +impl AuthorizationUpdateInternal { + pub fn create_authorization(self, source: Authorization) -> Authorization { + Authorization { + status: self.status.unwrap_or(source.status), + error_code: self.error_code.or(source.error_code), + error_message: self.error_message.or(source.error_message), + modified_at: self.modified_at.unwrap_or(common_utils::date_time::now()), + connector_authorization_id: self + .connector_authorization_id + .or(source.connector_authorization_id), + ..source + } + } +} + impl From<AuthorizationUpdate> for AuthorizationUpdateInternal { fn from(authorization_child_update: AuthorizationUpdate) -> Self { let now = Some(common_utils::date_time::now()); diff --git a/crates/router/src/db/authorization.rs b/crates/router/src/db/authorization.rs index f24daaf718a..d167d177537 100644 --- a/crates/router/src/db/authorization.rs +++ b/crates/router/src/db/authorization.rs @@ -1,3 +1,4 @@ +use diesel_models::authorization::AuthorizationUpdateInternal; use error_stack::IntoReport; use super::{MockDb, Store}; @@ -77,28 +78,71 @@ impl AuthorizationInterface for Store { impl AuthorizationInterface for MockDb { async fn insert_authorization( &self, - _authorization: storage::AuthorizationNew, + authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut authorizations = self.authorizations.lock().await; + if authorizations.iter().any(|authorization_inner| { + authorization_inner.authorization_id == authorization.authorization_id + }) { + Err(errors::StorageError::DuplicateValue { + entity: "authorization_id", + key: None, + })? + } + let authorization = storage::Authorization { + authorization_id: authorization.authorization_id, + merchant_id: authorization.merchant_id, + payment_id: authorization.payment_id, + amount: authorization.amount, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + status: authorization.status, + error_code: authorization.error_code, + error_message: authorization.error_message, + connector_authorization_id: authorization.connector_authorization_id, + previously_authorized_amount: authorization.previously_authorized_amount, + }; + authorizations.push(authorization.clone()); + Ok(authorization) } async fn find_all_authorizations_by_merchant_id_payment_id( &self, - _merchant_id: &str, - _payment_id: &str, + merchant_id: &str, + payment_id: &str, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let authorizations = self.authorizations.lock().await; + let authorizations_found: Vec<storage::Authorization> = authorizations + .iter() + .filter(|a| a.merchant_id == merchant_id && a.payment_id == payment_id) + .cloned() + .collect(); + + Ok(authorizations_found) } async fn update_authorization_by_merchant_id_authorization_id( &self, - _merchant_id: String, - _authorization_id: String, - _authorization: storage::AuthorizationUpdate, + merchant_id: String, + authorization_id: String, + authorization_update: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut authorizations = self.authorizations.lock().await; + authorizations + .iter_mut() + .find(|authorization| authorization.authorization_id == authorization_id && authorization.merchant_id == merchant_id) + .map(|authorization| { + let authorization_updated = + AuthorizationUpdateInternal::from(authorization_update) + .create_authorization(authorization.clone()); + *authorization = authorization_updated.clone(); + authorization_updated + }) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id}" + )) + .into(), + ) } } diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index e22d39ce70c..a6ba763bd91 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -43,6 +43,7 @@ pub struct MockDb { pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>, pub users: Arc<Mutex<Vec<store::user::User>>>, pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>, + pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>, pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>, } @@ -79,6 +80,7 @@ impl MockDb { organizations: Default::default(), users: Default::default(), user_roles: Default::default(), + authorizations: Default::default(), dashboard_metadata: Default::default(), }) }
2023-12-16T23:57:21Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implement AuthorizationInterface for MockDb ### 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
dc0e40d54bcff26c9996db6adc0a6071dc37ded0
juspay/hyperswitch
juspay__hyperswitch-3065
Bug: [REFACTOR] Make the `card_holder_name` optional for card details in the payment APIs ### Description We currently have the `card_holder_name` as mandatory for cards in the payment APIs. We currently do not mandatorily collect it for every payment so this causes the SDK to have to send an empty string for payments where the card holder name is not collected. We want to refactor this to allow for `null` values to avoid the need to send empty strings for the SDK.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 93c97cbd443..b19f4d7b7db 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -682,7 +682,7 @@ pub struct Card { /// The card holder's name #[schema(value_type = String, example = "John Test")] - pub card_holder_name: Secret<String>, + pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 3c7d5f2918f..38007a3110d 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -118,7 +118,7 @@ impl From<StripeCard> for payments::Card { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, - card_holder_name: card.holder_name.unwrap_or("name".to_string().into()), + card_holder_name: card.holder_name, card_cvc: card.cvc, card_issuer: None, card_network: None, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 9d3f74af8cb..4c99d0cb00b 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -95,7 +95,7 @@ impl From<StripeCard> for payments::Card { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, - card_holder_name: masking::Secret::new("stripe_cust".to_owned()), + card_holder_name: Some(masking::Secret::new("stripe_cust".to_owned())), card_cvc: card.cvc, card_issuer: None, card_network: None, diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 9cfb657bdca..53639f268c8 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -254,7 +254,9 @@ impl TryFrom<api_models::payments::Card> for PaymentDetails { fn try_from(card_data: api_models::payments::Card) -> Result<Self, Self::Error> { Ok(Self::AciCard(Box::new(CardDetails { card_number: card_data.card_number, - card_holder: card_data.card_holder_name, + card_holder: card_data + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, card_expiry_month: card_data.card_exp_month, card_expiry_year: card_data.card_exp_year, card_cvv: card_data.card_cvc, diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 2d50569f9a4..4729bfa5a6e 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -5,7 +5,7 @@ use masking::{PeekInterface, Secret}; use serde::{Deserialize, Deserializer, Serialize}; use crate::{ - connector::utils::{BrowserInformationData, PaymentsAuthorizeRequestData}, + connector::utils::{self, BrowserInformationData, PaymentsAuthorizeRequestData}, consts, core::errors, services, @@ -117,7 +117,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest { enums::AuthenticationType::NoThreeDs => None, }; let bambora_card = BamboraCard { - name: req_card.card_holder_name, + name: req_card + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index f6c1bfc46b0..d1201309637 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -867,7 +867,9 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { expiration_year: card_data.card_exp_year, expiration_month: card_data.card_exp_month, cvv: card_data.card_cvc, - cardholder_name: card_data.card_holder_name, + cardholder_name: card_data + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, }, }; Ok(Self { diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 92d01cfe56d..25462c758f1 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use url::Url; use crate::{ - connector::utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, + connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, core::errors, services, types::{self, api, storage::enums}, @@ -125,7 +125,10 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP document: get_doc_from_currency(country.to_string()), }, card: Some(Card { - holder_name: ccard.card_holder_name.clone(), + holder_name: ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: ccard.card_number.clone(), cvv: ccard.card_cvc.clone(), expiration_month: ccard.card_exp_month.clone(), diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs index 3c7bd2e09d9..bbb3b10c8e0 100644 --- a/crates/router/src/connector/dummyconnector/transformers.rs +++ b/crates/router/src/connector/dummyconnector/transformers.rs @@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize}; use url::Url; use crate::{ + connector::utils, core::errors, services, types::{self, api, storage::enums}, @@ -83,15 +84,18 @@ pub struct DummyConnectorCard { cvc: Secret<String>, } -impl From<api_models::payments::Card> for DummyConnectorCard { - fn from(value: api_models::payments::Card) -> Self { - Self { - name: value.card_holder_name, +impl TryFrom<api_models::payments::Card> for DummyConnectorCard { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(value: api_models::payments::Card) -> Result<Self, Self::Error> { + Ok(Self { + name: value + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: value.card_number, expiry_month: value.card_exp_month, expiry_year: value.card_exp_year, cvc: value.card_cvc, - } + }) } } @@ -151,7 +155,7 @@ impl<const T: u8> TryFrom<&types::PaymentsAuthorizeRouterData> .payment_method_data { api::PaymentMethodData::Card(ref req_card) => { - Ok(PaymentMethodData::Card(req_card.clone().into())) + Ok(PaymentMethodData::Card(req_card.clone().try_into()?)) } api::PaymentMethodData::Wallet(ref wallet_data) => { Ok(PaymentMethodData::Wallet(wallet_data.clone().try_into()?)) diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 4bb354f6cda..411457fab67 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -82,7 +82,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { let address = item.get_billing_address()?; let card = Card { card_type, - name_on_card: ccard.card_holder_name.clone(), + name_on_card: ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, account_number: ccard.card_number.clone(), expire_month: ccard.card_exp_month.clone(), expire_year: ccard.card_exp_year.clone(), diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index 62fb94e236a..c1151adcf6d 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -286,7 +286,10 @@ impl TryFrom<&types::TokenizationRouterData> for MollieCardTokenRequest { match item.request.payment_method_data.clone() { api_models::payments::PaymentMethodData::Card(ccard) => { let auth = MollieAuthType::try_from(&item.connector_auth_type)?; - let card_holder = ccard.card_holder_name.clone(); + let card_holder = ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?; let card_number = ccard.card_number.clone(); let card_expiry_date = ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned()); diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index b478d63e0f1..e2262e7b895 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -200,7 +200,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { _ => ( match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard { - name_on_card: req_card.card_holder_name.clone(), + name_on_card: req_card + .card_holder_name + .clone() + .ok_or_else(conn_utils::missing_field_err("card_holder_name"))?, number_plain: req_card.card_number.clone(), expiry_month: req_card.card_exp_month.clone(), expiry_year: req_card.get_expiry_year_4_digit(), diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 73e039c6339..4ed6b25b136 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1000,7 +1000,7 @@ impl From<NuveiCardDetails> for PaymentOption { Self { card: Some(Card { card_number: Some(card.card_number), - card_holder_name: Some(card.card_holder_name), + card_holder_name: card.card_holder_name, expiration_month: Some(card.card_exp_month), expiration_year: Some(card.card_exp_year), three_d: card_details.three_d, diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index 7b633f6aa64..a0e3877f82b 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -29,7 +29,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(req_card) => { let card = OpayoCard { - name: req_card.card_holder_name, + name: req_card + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 0170d18ecb4..8b4f4a46959 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -241,7 +241,10 @@ fn get_payment_method_data( let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?; let payeezy_card = PayeezyCard { card_type, - cardholder_name: card.card_holder_name.clone(), + cardholder_name: card + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, card_number: card.card_number.clone(), exp_date: card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string()), cvv: card.card_cvc.clone(), diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 8b6a2297d09..0871bc5097a 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -443,7 +443,10 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP let payment_source = Some(PaymentSourceItem::Card(CardRequest { billing_address: get_address_info(item.router_data.address.billing.as_ref())?, expiry, - name: ccard.card_holder_name.clone(), + name: ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: Some(ccard.card_number.clone()), security_code: Some(ccard.card_cvc.clone()), attributes, diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index e0ecd81c7e5..6d5a756c571 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -101,7 +101,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let source = match item.request.payment_method_data.clone() { - api::PaymentMethodData::Card(card) => Ok(Source::from(&card)), + api::PaymentMethodData::Card(card) => Source::try_from(&card), api::PaymentMethodData::Wallet(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::PayLater(_) @@ -211,15 +211,19 @@ impl TryFrom<&types::BrowserInformation> for BrowserInfo { }) }*/ -impl From<&Card> for Source { - fn from(card: &Card) -> Self { +impl TryFrom<&Card> for Source { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(card: &Card) -> Result<Self, Self::Error> { let card = PowertranzCard { - cardholder_name: card.card_holder_name.clone(), + cardholder_name: card + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, card_pan: card.card_number.clone(), card_expiration: card.get_expiry_date_as_yymm(), card_cvv: card.card_cvc.clone(), }; - Self::Card(card) + Ok(Self::Card(card)) } } diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 193eb819892..aab47bc8b21 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -4,7 +4,7 @@ use time::PrimitiveDateTime; use url::Url; use crate::{ - connector::utils::PaymentsAuthorizeRequestData, + connector::utils::{self, PaymentsAuthorizeRequestData}, consts, core::errors, pii::Secret, @@ -131,7 +131,10 @@ impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPay number: ccard.card_number.to_owned(), expiration_month: ccard.card_exp_month.to_owned(), expiration_year: ccard.card_exp_year.to_owned(), - name: ccard.card_holder_name.to_owned(), + name: ccard + .card_holder_name + .to_owned() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, cvv: ccard.card_cvc.to_owned(), }), address: None, diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index ce68aad25c5..2b89e7ebf6c 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -296,7 +296,10 @@ impl<T> number: card.card_number.clone(), exp_month: card.card_exp_month.clone(), exp_year: card.card_exp_year.clone(), - cardholder_name: card.card_holder_name.clone(), + cardholder_name: card + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, }; if item.is_three_ds() { Ok(Self::Cards3DSRequest(Box::new(Cards3DSRequest { diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 2fd3b3474ea..7395172239e 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -226,7 +226,9 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { let stax_card_data = StaxTokenizeData { card_exp: card_data .get_card_expiry_month_year_2_digit_with_delimiter("".to_string()), - person_name: card_data.card_holder_name, + person_name: card_data + .card_holder_name + .ok_or_else(missing_field_err("card_holder_name"))?, card_number: card_data.card_number, card_cvv: card_data.card_cvc, customer_id: Secret::new(customer_id), diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index b5739fe857a..d9e9d1ff7c0 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -351,7 +351,10 @@ fn make_card_request( let expiry_date: Secret<String> = Secret::new(secret_value); let card = Card { card_number: ccard.card_number.clone(), - cardholder_name: ccard.card_holder_name.clone(), + cardholder_name: ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, cvv: ccard.card_cvc.clone(), expiry_date, }; diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 5ad78c9d730..c71632c9b06 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -51,7 +51,10 @@ impl Vaultable for api::Card { card_number: self.card_number.peek().clone(), exp_year: self.card_exp_year.peek().clone(), exp_month: self.card_exp_month.peek().clone(), - name_on_card: Some(self.card_holder_name.peek().clone()), + name_on_card: self + .card_holder_name + .clone() + .map(|name| name.peek().clone()), nickname: None, card_last_four: None, card_token: None, @@ -99,7 +102,7 @@ impl Vaultable for api::Card { .attach_printable("Invalid card number format from the mock locker")?, card_exp_month: value1.exp_month.into(), card_exp_year: value1.exp_year.into(), - card_holder_name: value1.name_on_card.unwrap_or_default().into(), + card_holder_name: value1.name_on_card.map(masking::Secret::new), card_cvc: value2.card_security_code.unwrap_or_default().into(), card_issuer: None, card_network: None, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 4e491964e96..866a0581e4e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -946,6 +946,42 @@ pub fn verify_mandate_details( ) } +// This function validates card_holder_name field to be either null or a non-empty string +pub fn validate_card_holder_name( + payment_method_data: Option<api::PaymentMethodData>, +) -> CustomResult<(), errors::ApiErrorResponse> { + if let Some(pmd) = payment_method_data { + match pmd { + // This validation would occur during payments create + api::PaymentMethodData::Card(card) => { + if let Some(name) = &card.card_holder_name { + if name.clone().expose().is_empty() { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "card_holder_name cannot be empty".to_string(), + }) + .into_report(); + } + } + } + + // This validation would occur during payments confirm + api::PaymentMethodData::CardToken(card) => { + if let Some(name) = card.card_holder_name { + if name.expose().is_empty() { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "card_holder_name cannot be empty".to_string(), + }) + .into_report(); + } + } + } + _ => (), + } + } + + Ok(()) +} + #[instrument(skip_all)] pub fn payment_attempt_status_fsm( payment_method_data: &Option<api::PaymentMethodData>, @@ -1033,7 +1069,7 @@ pub(crate) async fn get_payment_method_create_request( card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), - card_holder_name: Some(card.card_holder_name.clone()), + card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), }; let customer_id = customer.customer_id.clone(); @@ -1404,21 +1440,25 @@ pub async fn retrieve_payment_method_with_temporary_token( let mut updated_card = card.clone(); let mut is_card_updated = false; - let name_on_card = if card.card_holder_name.clone().expose().is_empty() { - card_token_data - .and_then(|token_data| token_data.card_holder_name.clone()) - .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) - .map(|name_on_card| { + // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked + // from payment_method.card_token object + let name_on_card = if let Some(name) = card.card_holder_name.clone() { + if name.expose().is_empty() { + card_token_data.and_then(|token_data| { is_card_updated = true; - name_on_card + token_data.card_holder_name.clone() }) + } else { + card.card_holder_name.clone() + } } else { - Some(card.card_holder_name.clone()) + card_token_data.and_then(|token_data| { + is_card_updated = true; + token_data.card_holder_name.clone() + }) }; - if let Some(name_on_card) = name_on_card { - updated_card.card_holder_name = name_on_card; - } + updated_card.card_holder_name = name_on_card; if let Some(token_data) = card_token_data { if let Some(cvc) = token_data.card_cvc.clone() { @@ -1487,23 +1527,21 @@ pub async fn retrieve_card_with_permanent_token( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?; - let name_on_card = if let Some(name_on_card) = card.name_on_card.clone() { - if card.name_on_card.unwrap_or_default().expose().is_empty() { - card_token_data - .and_then(|token_data| token_data.card_holder_name.clone()) - .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) + // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked + // from payment_method.card_token object + let name_on_card = if let Some(name) = card.name_on_card.clone() { + if name.expose().is_empty() { + card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) } else { - Some(name_on_card) + card.name_on_card } } else { - card_token_data - .and_then(|token_data| token_data.card_holder_name.clone()) - .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) + card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) }; let api_card = api::Card { card_number: card.card_number, - card_holder_name: name_on_card.unwrap_or(masking::Secret::from("".to_string())), + card_holder_name: name_on_card, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_cvc: card_token_data @@ -3324,7 +3362,7 @@ pub async fn get_additional_payment_data( bank_code: card_data.bank_code.to_owned(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: Some(card_data.card_holder_name.clone()), + card_holder_name: card_data.card_holder_name.clone(), last4: last4.clone(), card_isin: card_isin.clone(), }, @@ -3352,7 +3390,7 @@ pub async fn get_additional_payment_data( card_isin: card_isin.clone(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: Some(card_data.card_holder_name.clone()), + card_holder_name: card_data.card_holder_name.clone(), }, )) }); @@ -3367,7 +3405,7 @@ pub async fn get_additional_payment_data( card_isin, card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: Some(card_data.card_holder_name.clone()), + card_holder_name: card_data.card_holder_name.clone(), }, ))) } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index af2a9fa49c8..612ddadc1c5 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -871,6 +871,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; + helpers::validate_card_holder_name(request.payment_method_data.clone())?; + let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index eb7f31ba24d..cbce6ba9e97 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -560,6 +560,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_amount_to_capture_and_capture_method(None, request)?; helpers::validate_card_data(request.payment_method_data.clone())?; + helpers::validate_card_holder_name(request.payment_method_data.clone())?; + helpers::validate_payment_method_fields_present(request)?; let mandate_type = diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index f1a35cffce8..84f11124c73 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -655,6 +655,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; + helpers::validate_card_holder_name(request.payment_method_data.clone())?; + let mandate_type = helpers::validate_mandate(request, false)?; Ok(( diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 2acf42fa479..9159abf4bd1 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -244,7 +244,7 @@ mod payments_test { card_number: "1234432112344321".to_string().try_into().unwrap(), card_exp_month: "12".to_string().into(), card_exp_year: "99".to_string().into(), - card_holder_name: "JohnDoe".to_string().into(), + card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())), card_cvc: "123".to_string().into(), card_issuer: Some("HDFC".to_string()), card_network: Some(api_models::enums::CardNetwork::Visa), diff --git a/crates/router/src/utils/verify_connector.rs b/crates/router/src/utils/verify_connector.rs index 6ad683d63ba..060f92d0e5a 100644 --- a/crates/router/src/utils/verify_connector.rs +++ b/crates/router/src/utils/verify_connector.rs @@ -20,7 +20,7 @@ pub fn generate_card_from_details( card_network: None, card_exp_year: masking::Secret::new(card_exp_year), card_exp_month: masking::Secret::new(card_exp_month), - card_holder_name: masking::Secret::new("HyperSwitch".to_string()), + card_holder_name: Some(masking::Secret::new("HyperSwitch".to_string())), nick_name: None, card_type: None, card_issuing_country: None, diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 7ddc504956f..dd8c1ed5f77 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -38,7 +38,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("999".to_string()), card_issuer: None, card_network: None, @@ -232,7 +232,7 @@ async fn payments_create_failure() { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("99".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 714dc0d7d67..14177e6fb50 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -126,7 +126,7 @@ impl AdyenTest { card_number: cards::CardNumber::from_str(card_number).unwrap(), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new(card_cvc.to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index 6e7f6c000d2..cfc4c0c003d 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -60,7 +60,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { card_number: cards::CardNumber::from_str("4035501000000008").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 4021d57d543..3ae4298e836 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -42,7 +42,7 @@ fn get_payment_method_data() -> api::Card { card_number: cards::CardNumber::from_str("5424000000000015").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), ..Default::default() } diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs index 30052d11da4..852b23f022c 100644 --- a/crates/router/tests/connectors/bluesnap.rs +++ b/crates/router/tests/connectors/bluesnap.rs @@ -400,7 +400,7 @@ async fn should_fail_payment_for_incorrect_cvc() { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -426,7 +426,7 @@ async fn should_fail_payment_for_invalid_exp_month() { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -452,7 +452,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 1394667718c..36d5f66dbcc 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -46,7 +46,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs index 5550ba12af8..7de81a8bed2 100644 --- a/crates/router/tests/connectors/payme.rs +++ b/crates/router/tests/connectors/payme.rs @@ -87,7 +87,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { card_cvc: Secret::new("123".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), ..utils::CCardType::default().0 }), amount: 1000, diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index 143f87fc575..c53f4e8d8b1 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -46,7 +46,7 @@ async fn should_only_authorize_payment() { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, @@ -74,7 +74,7 @@ async fn should_authorize_and_capture_payment() { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 7e5cfeb4397..d3b20b01e4c 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -869,7 +869,7 @@ impl Default for CCardType { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("999".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index fd697f95b75..6a92e0dc93f 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -71,7 +71,7 @@ impl WorldlineTest { card_number: cards::CardNumber::from_str(card_number).unwrap(), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new(card_cvc.to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 9d48aaddd45..8f5ac25736c 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -320,7 +320,7 @@ async fn payments_create_core() { card_number: "4242424242424242".to_string().try_into().unwrap(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), - card_holder_name: "Arun Raj".to_string().into(), + card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())), card_cvc: "123".to_string().into(), card_issuer: None, card_network: None, @@ -496,7 +496,7 @@ async fn payments_create_core_adyen_no_redirect() { card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(), card_exp_month: "03".to_string().into(), card_exp_year: "2030".to_string().into(), - card_holder_name: "JohnDoe".to_string().into(), + card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())), card_cvc: "737".to_string().into(), card_issuer: None, card_network: None, diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 42e5524a15d..89ac522d237 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -80,7 +80,7 @@ async fn payments_create_core() { card_number: "4242424242424242".to_string().try_into().unwrap(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), - card_holder_name: "Arun Raj".to_string().into(), + card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())), card_cvc: "123".to_string().into(), card_issuer: None, card_network: None, @@ -263,7 +263,7 @@ async fn payments_create_core_adyen_no_redirect() { card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(), card_exp_month: "03".to_string().into(), card_exp_year: "2030".to_string().into(), - card_holder_name: "JohnDoe".to_string().into(), + card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())), card_cvc: "737".to_string().into(), bank_code: None, card_issuer: None,
2023-12-06T16:46:54Z
## 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 --> We currently have the `card_holder_name` as mandatory for cards in the payment APIs. We currently do not mandatorily collect it for every payment so this causes the SDK to have to send an empty string for payments where the card holder name is not collected. This PR includes following changes: * Refactoring to allow `card_holder_name` field for null values to avoid the need to send empty strings for the SDK. * Throw error when `card_holder_name` is not passed for the connector in which `card_holder_name` is a required field. * Allow sending either `null` or `non-empty string` for `card_holder_name` field. If an empty string is passed, throws an error Above changes apply during both payments `create` and `confirm` ### 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)? --> 1. Create merchant account ``` curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1701880995", "locker_id": "m0010", "merchant_name": "Chethan", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` 2. Create API key ``` curl --location 'http://localhost:8080/api_keys/merchant_1701880168' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2024-07-06T06:15:00.000Z" }' ``` 3. Create MCA account with ACI as connector (because `card_holder_name` is required field for ACI) ``` curl --location 'http://localhost:8080/account/merchant_1701880168/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "aci", "connector_account_details": { "api_key": "Bearer OGFjN2E0Yzk3ZDA0NDMwNTAxN2QwNTMxNDQxMjA5ZjF8emV6N1lTUHNEaw==", "auth_type": "BodyKey", "key1": "8ac7a4c97d044305017d053142b009ed" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "ali_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "mb_way", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "interac", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" } }' ``` 4. Make a payment without passing `card_holder_name` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_dk7ZaxtZSxglnD4CUK3R2mPZBfOczCfAytnTyZZ0gm2u5sJqLyo4w5CiEJLIRT5e' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "setup_future_usage": "on_session", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Above API should throw below error ![error](https://github.com/juspay/hyperswitch/assets/70657455/4b38f4d1-3623-4971-9673-cd19737b22fd) 5. You can check this flow for connector in which `card_holder_name` is not a required field (like stripe). In this case you need not pass the `card_holder_name` as it is made optional here. 6. If u try to make a payment with `card_holder_name` empty, it will throw below error ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_98wh5QexR03yFlBCDPr0eSkvWH69UB1DwpSQyGK9qBSMPTeo2vWBmD0D3yAHdl54' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123", "card_holder_name": "" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/4fc50540-8e67-4d8a-a52d-0b5c4aff1786) 7. You can try above flow with `/confirm` route too ``` curl --location 'http://localhost:8080/payments/pay_QXQSt3xFUpR1DRWWkCwW/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_98wh5QexR03yFlBCDPr0eSkvWH69UB1DwpSQyGK9qBSMPTeo2vWBmD0D3yAHdl54' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_token": "token_WuamozY38qmQBbPXn7aS", "payment_method_data": { "card_token": { "card_holder_name": "" } } }' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
777cd5cdc2342fb7195a06505647fa331725e1dd
juspay/hyperswitch
juspay__hyperswitch-3007
Bug: [Feature]: [Braintree] Sync with Hyperswitch Reference ### :memo: Feature Description - In Hyperswitch, we retrieve transaction status in two ways: 1. Using `transaction_id` which is generated by Connectors 2. Using our `reference_id` which can be passed to Connectors during payment creation - If supported, the request for retrieving Payments and Refunds should use the Hyperswitch's `reference_id`. This would assist in obtaining the payment/refund status in the event we failed to get it due to timeout, connection failure, etc. ### :hammer: Possible Implementation - If the connector supports retrieving payments and refunds using our reference_id i.e `connector_request_reference_id` , we should utilize this functionality instead of exclusively relying on the connector_transaction_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 44daef94e8a..f4bd62add3b 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -228,17 +228,16 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { + let id = item.response.transaction.id.clone(); Ok(Self { status: enums::AttemptStatus::from(item.response.transaction.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transaction.id, - ), + resource_id: types::ResponseId::ConnectorTransactionId(id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(id), incremental_authorization_allowed: None, }), ..item.data
2023-12-02T09:33:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description fixes #3007 ### 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)? --> test case - Make a transaction, in response for reference field, we should see connector transaction id. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cfafd5cd29857283d57731dda7c5a332a493f531
juspay/hyperswitch
juspay__hyperswitch-3001
Bug: [REFACTOR]: Field Type for OpenBankingUk Payment Method ### :memo: Feature Description - In OpenBankingUk, we had two fields issuer and country. As of now these are mandatory fields. But these fields are not required for all the connector, as I came with connector Volt which don't need these fields in their request . ### :hammer: Possible Implementation - We can make this fields optional and handle the cases accordingly for the connectors which already has `open_banking_uk` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? Yes
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index bd4c59211e2..5ecbf795ac5 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1204,10 +1204,10 @@ pub enum BankRedirectData { OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] - issuer: api_enums::BankNames, + issuer: Option<api_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] - country: api_enums::CountryAlpha2, + country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index cfa60111267..4b3fcc85132 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -879,7 +879,126 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer { api::enums::BankNames::TsbBank => Ok(Self::TsbBank), api::enums::BankNames::TescoBank => Ok(Self::TescoBank), api::enums::BankNames::UlsterBank => Ok(Self::UlsterBank), - _ => Err(errors::ConnectorError::NotSupported { + enums::BankNames::AmericanExpress + | enums::BankNames::AffinBank + | enums::BankNames::AgroBank + | enums::BankNames::AllianceBank + | enums::BankNames::AmBank + | enums::BankNames::BankOfAmerica + | enums::BankNames::BankIslam + | enums::BankNames::BankMuamalat + | enums::BankNames::BankRakyat + | enums::BankNames::BankSimpananNasional + | enums::BankNames::BlikPSP + | enums::BankNames::CapitalOne + | enums::BankNames::Chase + | enums::BankNames::Citi + | enums::BankNames::CimbBank + | enums::BankNames::Discover + | enums::BankNames::NavyFederalCreditUnion + | enums::BankNames::PentagonFederalCreditUnion + | enums::BankNames::SynchronyBank + | enums::BankNames::WellsFargo + | enums::BankNames::AbnAmro + | enums::BankNames::AsnBank + | enums::BankNames::Bunq + | enums::BankNames::Handelsbanken + | enums::BankNames::HongLeongBank + | enums::BankNames::Ing + | enums::BankNames::Knab + | enums::BankNames::KuwaitFinanceHouse + | enums::BankNames::Moneyou + | enums::BankNames::Rabobank + | enums::BankNames::Regiobank + | enums::BankNames::SnsBank + | enums::BankNames::TriodosBank + | enums::BankNames::VanLanschot + | enums::BankNames::ArzteUndApothekerBank + | enums::BankNames::AustrianAnadiBankAg + | enums::BankNames::BankAustria + | enums::BankNames::Bank99Ag + | enums::BankNames::BankhausCarlSpangler + | enums::BankNames::BankhausSchelhammerUndSchatteraAg + | enums::BankNames::BankMillennium + | enums::BankNames::BankPEKAOSA + | enums::BankNames::BawagPskAg + | enums::BankNames::BksBankAg + | enums::BankNames::BrullKallmusBankAg + | enums::BankNames::BtvVierLanderBank + | enums::BankNames::CapitalBankGraweGruppeAg + | enums::BankNames::CeskaSporitelna + | enums::BankNames::Dolomitenbank + | enums::BankNames::EasybankAg + | enums::BankNames::EPlatbyVUB + | enums::BankNames::ErsteBankUndSparkassen + | enums::BankNames::FrieslandBank + | enums::BankNames::HypoAlpeadriabankInternationalAg + | enums::BankNames::HypoNoeLbFurNiederosterreichUWien + | enums::BankNames::HypoOberosterreichSalzburgSteiermark + | enums::BankNames::HypoTirolBankAg + | enums::BankNames::HypoVorarlbergBankAg + | enums::BankNames::HypoBankBurgenlandAktiengesellschaft + | enums::BankNames::KomercniBanka + | enums::BankNames::MBank + | enums::BankNames::MarchfelderBank + | enums::BankNames::Maybank + | enums::BankNames::OberbankAg + | enums::BankNames::OsterreichischeArzteUndApothekerbank + | enums::BankNames::OcbcBank + | enums::BankNames::PayWithING + | enums::BankNames::PlaceZIPKO + | enums::BankNames::PlatnoscOnlineKartaPlatnicza + | enums::BankNames::PosojilnicaBankEGen + | enums::BankNames::PostovaBanka + | enums::BankNames::PublicBank + | enums::BankNames::RaiffeisenBankengruppeOsterreich + | enums::BankNames::RhbBank + | enums::BankNames::SchelhammerCapitalBankAg + | enums::BankNames::StandardCharteredBank + | enums::BankNames::SchoellerbankAg + | enums::BankNames::SpardaBankWien + | enums::BankNames::SporoPay + | enums::BankNames::TatraPay + | enums::BankNames::Viamo + | enums::BankNames::VolksbankGruppe + | enums::BankNames::VolkskreditbankAg + | enums::BankNames::VrBankBraunau + | enums::BankNames::UobBank + | enums::BankNames::PayWithAliorBank + | enums::BankNames::BankiSpoldzielcze + | enums::BankNames::PayWithInteligo + | enums::BankNames::BNPParibasPoland + | enums::BankNames::BankNowySA + | enums::BankNames::CreditAgricole + | enums::BankNames::PayWithBOS + | enums::BankNames::PayWithCitiHandlowy + | enums::BankNames::PayWithPlusBank + | enums::BankNames::ToyotaBank + | enums::BankNames::VeloBank + | enums::BankNames::ETransferPocztowy24 + | enums::BankNames::PlusBank + | enums::BankNames::EtransferPocztowy24 + | enums::BankNames::BankiSpbdzielcze + | enums::BankNames::BankNowyBfgSa + | enums::BankNames::GetinBank + | enums::BankNames::Blik + | enums::BankNames::NoblePay + | enums::BankNames::IdeaBank + | enums::BankNames::EnveloBank + | enums::BankNames::NestPrzelew + | enums::BankNames::MbankMtransfer + | enums::BankNames::Inteligo + | enums::BankNames::PbacZIpko + | enums::BankNames::BnpParibas + | enums::BankNames::BankPekaoSa + | enums::BankNames::VolkswagenBank + | enums::BankNames::AliorBank + | enums::BankNames::Boz + | enums::BankNames::BangkokBank + | enums::BankNames::KrungsriBank + | enums::BankNames::KrungThaiBank + | enums::BankNames::TheSiamCommercialBank + | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotSupported { message: String::from("BankRedirect"), connector: "Adyen", })?, @@ -2102,7 +2221,12 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod ), api_models::payments::BankRedirectData::OpenBankingUk { issuer, .. } => Ok( AdyenPaymentMethod::OpenBankingUK(Box::new(OpenBankingUKData { - issuer: OpenBankingUKIssuer::try_from(issuer)?, + issuer: match issuer { + Some(bank_name) => OpenBankingUKIssuer::try_from(bank_name)?, + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "issuer", + })?, + }, })), ), api_models::payments::BankRedirectData::Sofort { .. } => Ok(AdyenPaymentMethod::Sofort), @@ -2580,7 +2704,7 @@ impl<'a> let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_return_url()?; let payment_method = AdyenPaymentMethod::try_from(bank_redirect_data)?; - let (shopper_locale, country) = get_redirect_extra_details(item.router_data); + let (shopper_locale, country) = get_redirect_extra_details(item.router_data)?; let line_items = Some(get_line_items(item)); Ok(AdyenPaymentRequest { @@ -2611,7 +2735,7 @@ impl<'a> fn get_redirect_extra_details( item: &types::PaymentsAuthorizeRouterData, -) -> (Option<String>, Option<api_enums::CountryAlpha2>) { +) -> Result<(Option<String>, Option<api_enums::CountryAlpha2>), errors::ConnectorError> { match item.request.payment_method_data { api_models::payments::PaymentMethodData::BankRedirect(ref redirect_data) => { match redirect_data { @@ -2619,17 +2743,20 @@ fn get_redirect_extra_details( country, preferred_language, .. - } => ( + } => Ok(( Some(preferred_language.to_string()), Some(country.to_owned()), - ), + )), api_models::payments::BankRedirectData::OpenBankingUk { country, .. } => { - (None, Some(country.to_owned())) + let country = country.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "country", + })?; + Ok((None, Some(country))) } - _ => (None, None), + _ => Ok((None, None)), } } - _ => (None, None), + _ => Ok((None, None)), } }
2023-11-28T10:01:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description In OpenBankingUk, we had two fields issuer and country. But these fields are not required for all the connector, I came with connector Volt which don't need these fields in their request so I made these fields optional. ### 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? Using Postman ## Test cases Test ` Open_banking_uk `for Volt and Adyen Coonector. Curl For Open Banking Uk for Adyen: `{ "amount": 6540, "currency": "GBP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com/", "payment_method": "bank_redirect", "payment_method_type": "open_banking_uk", "payment_method_data": { "bank_redirect": { "open_banking_uk": { "issuer": "open_bank_success", "country": "GB" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "GB", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "GB", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c05432c0bd70f222c2f898ce2cbb47a46364a490
juspay/hyperswitch
juspay__hyperswitch-3003
Bug: [BUG]: [Dlocal] connector transaction id fix ### Bug Description The Dlocal connector Transaction ID wasn't correctly populated, causing failures in subsequent operations like capture, refund, and 3DS redirection. ### Expected Behavior Transaction id should be mapped to `item.response.id` in connector response and all subsequent actions should be functional . ### Actual Behavior The Dlocal connector Transaction ID wasn't correctly populated, causing failures in subsequent operations like capture, refund, and 3DS redirection. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' Try making 3ds payment via Dlocal ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 668a335cce8..66cf413e991 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -302,7 +302,7 @@ pub struct DlocalPaymentsResponse { status: DlocalPaymentStatus, id: String, three_dsecure: Option<ThreeDSecureResData>, - order_id: String, + order_id: Option<String>, } impl<F, T> @@ -322,12 +322,12 @@ impl<F, T> }); let response = types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id.clone()), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), + connector_response_reference_id: item.response.order_id.clone(), }; Ok(Self { status: enums::AttemptStatus::from(item.response.status), @@ -341,7 +341,7 @@ impl<F, T> pub struct DlocalPaymentsSyncResponse { status: DlocalPaymentStatus, id: String, - order_id: String, + order_id: Option<String>, } impl<F, T> @@ -361,14 +361,12 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.order_id.clone(), - ), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), + connector_response_reference_id: item.response.order_id.clone(), }), ..item.data }) @@ -379,7 +377,7 @@ impl<F, T> pub struct DlocalPaymentsCaptureResponse { status: DlocalPaymentStatus, id: String, - order_id: String, + order_id: Option<String>, } impl<F, T> @@ -399,14 +397,12 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.order_id.clone(), - ), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), + connector_response_reference_id: item.response.order_id.clone(), }), ..item.data })
2023-11-14T19:49:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Fix: Dlocal Connector Transaction ID Population 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? A.) The Dlocal connector Transaction ID wasn't correctly populated, causing failures in subsequent operations like capture, refund, and 3DS redirection. This fix ensures the proper population of the Transaction ID, resolving the associated failures. <!-- If it fixes an open issue, please link to the issue here. No If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## 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 manually --> Executed the following test scenario using the Postman collection: - Initiated a 3DS-authorized transaction - Successfully completed the authorization process - Captured the payment" <img width="1512" alt="Dlocal capture" src="https://github.com/juspay/hyperswitch/assets/50401745/711a23ce-05d3-43a6-828b-db2d7ca77522"> <img width="1512" alt="dlocal after redirection" src="https://github.com/juspay/hyperswitch/assets/50401745/b801aed1-7768-47b0-ae4a-44ef1206621c"> <img width="1512" alt="Dlocal 3ds" src="https://github.com/juspay/hyperswitch/assets/50401745/4ffc3397-3f79-4d2a-a275-35134c469030"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
496245d990e123b626089e70c848856ace295fb5
juspay/hyperswitch
juspay__hyperswitch-3046
Bug: [FEATURE] Migrate PaymentMethodAuth to OSS ### Feature Description Migrating PM auth services to OSS ### Possible Implementation Migration of PM auth crate and dependent changes ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index d2e8d9dd5df..307a5ca2398 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -405,6 +405,8 @@ dependencies = [ "common_utils", "error-stack", "euclid", + "frunk", + "frunk_core", "masking", "mime", "reqwest", @@ -4436,6 +4438,27 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "pm_auth" +version = "0.1.0" +dependencies = [ + "api_models", + "async-trait", + "bytes 1.5.0", + "common_enums", + "common_utils", + "error-stack", + "http", + "masking", + "mime", + "router_derive", + "router_env", + "serde", + "serde_json", + "strum 0.24.1", + "thiserror", +] + [[package]] name = "png" version = "0.16.8" @@ -5110,6 +5133,7 @@ dependencies = [ "num_cpus", "once_cell", "openssl", + "pm_auth", "qrcode", "rand 0.8.5", "rand_chacha 0.3.1", diff --git a/config/config.example.toml b/config/config.example.toml index 1897c935581..7a50c23f484 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -122,7 +122,7 @@ kms_encrypted_recon_admin_api_key = "" # Base64-encoded (KMS encrypted) cipher # like card details [locker] host = "" # Locker host -host_rs = "" # Rust Locker host +host_rs = "" # Rust Locker host mock_locker = true # Emulate a locker locally using Postgres basilisk_host = "" # Basilisk host locker_signing_key_id = "1" # Key_id to sign basilisk hs locker @@ -461,6 +461,10 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" #Private key [payment_link] sdk_url = "http://localhost:9090/dist/HyperLoader.js" +[payment_method_auth] +redis_expiry = 900 +pm_auth_key = "Some_pm_auth_key" + # Analytics configuration. [analytics] source = "sqlx" # The Analytics source/strategy to be used diff --git a/config/development.toml b/config/development.toml index 4ee33795676..15acfdee9b7 100644 --- a/config/development.toml +++ b/config/development.toml @@ -470,6 +470,10 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" [payment_link] sdk_url = "http://localhost:9090/dist/HyperLoader.js" +[payment_method_auth] +redis_expiry = 900 +pm_auth_key = "Some_pm_auth_key" + [lock_settings] redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 55fc62329d4..5eec8d733d6 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -330,6 +330,10 @@ payout_connector_list = "wise" [multiple_api_version_supported_connectors] supported_connectors = "braintree" +[payment_method_auth] +redis_expiry = 900 +pm_auth_key = "Some_pm_auth_key" + [lock_settings] redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 116aad25d5c..afba129b601 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -30,6 +30,8 @@ strum = { version = "0.25", features = ["derive"] } time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] } url = { version = "2.4.0", features = ["serde"] } utoipa = { version = "3.3.0", features = ["preserve_order"] } +frunk = "0.4.1" +frunk_core = "0.4.1" # First party crates cards = { version = "0.1.0", path = "../cards" } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 17787929a46..21586054055 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + pub use common_enums::*; use utoipa::ToSchema; @@ -500,3 +502,26 @@ pub enum LockerChoice { Basilisk, Tartarus, } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, + ToSchema, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum PmAuthConnectors { + Plaid, +} + +pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnectors> { + PmAuthConnectors::from_str(connector_name).ok() +} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index ce3c11d9c2f..935944cf74c 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -23,6 +23,7 @@ pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; +pub mod pm_auth; pub mod refunds; pub mod routing; pub mod surcharge_decision_configs; diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs new file mode 100644 index 00000000000..7044bd8d335 --- /dev/null +++ b/crates/api_models/src/pm_auth.rs @@ -0,0 +1,57 @@ +use common_enums::{PaymentMethod, PaymentMethodType}; +use common_utils::{ + events::{ApiEventMetric, ApiEventsType}, + impl_misc_api_event_type, +}; + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct LinkTokenCreateRequest { + pub language: Option<String>, // optional language field to be passed + pub client_secret: Option<String>, // client secret to be passed in req body + pub payment_id: String, // payment_id to be passed in req body for redis pm_auth connector name fetch + pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector + pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct LinkTokenCreateResponse { + pub link_token: String, // link_token received in response + pub connector: String, // pm_auth connector name in response +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] + +pub struct ExchangeTokenCreateRequest { + pub public_token: String, + pub client_secret: Option<String>, + pub payment_id: String, + pub payment_method: PaymentMethod, + pub payment_method_type: PaymentMethodType, +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct ExchangeTokenCreateResponse { + pub access_token: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentMethodAuthConfig { + pub enabled_payment_methods: Vec<PaymentMethodAuthConnectorChoice>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentMethodAuthConnectorChoice { + pub payment_method: PaymentMethod, + pub payment_method_type: PaymentMethodType, + pub connector_name: String, + pub mca_id: String, +} + +impl_misc_api_event_type!( + LinkTokenCreateRequest, + LinkTokenCreateResponse, + ExchangeTokenCreateRequest, + ExchangeTokenCreateResponse +); diff --git a/crates/pm_auth/Cargo.toml b/crates/pm_auth/Cargo.toml new file mode 100644 index 00000000000..a9aebc5b540 --- /dev/null +++ b/crates/pm_auth/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "pm_auth" +description = "Open banking services" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +readme = "README.md" + +[dependencies] +# First party crates +api_models = { version = "0.1.0", path = "../api_models" } +common_enums = { version = "0.1.0", path = "../common_enums" } +common_utils = { version = "0.1.0", path = "../common_utils" } +masking = { version = "0.1.0", path = "../masking" } +router_derive = { version = "0.1.0", path = "../router_derive" } +router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } + +# Third party crates +async-trait = "0.1.66" +bytes = "1.4.0" +error-stack = "0.3.1" +http = "0.2.9" +mime = "0.3.17" +serde = "1.0.159" +serde_json = "1.0.91" +strum = { version = "0.24.1", features = ["derive"] } +thiserror = "1.0.43" diff --git a/crates/pm_auth/README.md b/crates/pm_auth/README.md new file mode 100644 index 00000000000..c630a7fe676 --- /dev/null +++ b/crates/pm_auth/README.md @@ -0,0 +1,3 @@ +# Payment Method Auth Services + +An open banking services for payment method auth validation diff --git a/crates/pm_auth/src/connector.rs b/crates/pm_auth/src/connector.rs new file mode 100644 index 00000000000..56aad846e24 --- /dev/null +++ b/crates/pm_auth/src/connector.rs @@ -0,0 +1,3 @@ +pub mod plaid; + +pub use self::plaid::Plaid; diff --git a/crates/pm_auth/src/connector/plaid.rs b/crates/pm_auth/src/connector/plaid.rs new file mode 100644 index 00000000000..d25aba881d2 --- /dev/null +++ b/crates/pm_auth/src/connector/plaid.rs @@ -0,0 +1,353 @@ +pub mod transformers; + +use std::fmt::Debug; + +use common_utils::{ + ext_traits::{BytesExt, Encode}, + request::{Method, Request, RequestBody, RequestBuilder}, +}; +use error_stack::ResultExt; +use masking::{Mask, Maskable}; +use transformers as plaid; + +use crate::{ + core::errors, + types::{ + self as auth_types, + api::{ + auth_service::{self, BankAccountCredentials, ExchangeToken, LinkToken}, + ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + }, + }, +}; + +#[derive(Debug, Clone)] +pub struct Plaid; + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + "Content-Type".to_string(), + self.get_content_type().to_string().into(), + )]; + + let mut auth = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut auth); + Ok(header) + } +} + +impl ConnectorCommon for Plaid { + fn id(&self) -> &'static str { + "plaid" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str { + "https://sandbox.plaid.com" + } + + fn get_auth_header( + &self, + auth_type: &auth_types::ConnectorAuthType, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + let auth = plaid::PlaidAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let client_id = auth.client_id.into_masked(); + let secret = auth.secret.into_masked(); + + Ok(vec![ + ("PLAID-CLIENT-ID".to_string(), client_id), + ("PLAID-SECRET".to_string(), secret), + ]) + } + + fn build_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + let response: plaid::PlaidErrorResponse = + res.response + .parse_struct("PlaidErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(auth_types::ErrorResponse { + status_code: res.status_code, + code: crate::consts::NO_ERROR_CODE.to_string(), + message: response.error_message, + reason: response.display_message, + }) + } +} + +impl auth_service::AuthService for Plaid {} +impl auth_service::AuthServiceLinkToken for Plaid {} + +impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse> + for Plaid +{ + fn get_headers( + &self, + req: &auth_types::LinkTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &auth_types::LinkTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "/link/token/create" + )) + } + + fn get_request_body( + &self, + req: &auth_types::LinkTokenRouterData, + ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> { + let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?; + let plaid_req = RequestBody::log_and_get_request_body( + &req_obj, + Encode::<plaid::PlaidLinkTokenRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(plaid_req)) + } + + fn build_request( + &self, + req: &auth_types::LinkTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&auth_types::PaymentAuthLinkTokenType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(auth_types::PaymentAuthLinkTokenType::get_headers( + self, req, connectors, + )?) + .body(auth_types::PaymentAuthLinkTokenType::get_request_body( + self, req, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &auth_types::LinkTokenRouterData, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> { + let response: plaid::PlaidLinkTokenResponse = res + .response + .parse_struct("PlaidLinkTokenResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + <auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl auth_service::AuthServiceExchangeToken for Plaid {} + +impl + ConnectorIntegration< + ExchangeToken, + auth_types::ExchangeTokenRequest, + auth_types::ExchangeTokenResponse, + > for Plaid +{ + fn get_headers( + &self, + req: &auth_types::ExchangeTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &auth_types::ExchangeTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "/item/public_token/exchange" + )) + } + + fn get_request_body( + &self, + req: &auth_types::ExchangeTokenRouterData, + ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> { + let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?; + let plaid_req = RequestBody::log_and_get_request_body( + &req_obj, + Encode::<plaid::PlaidExchangeTokenRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(plaid_req)) + } + + fn build_request( + &self, + req: &auth_types::ExchangeTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&auth_types::PaymentAuthExchangeTokenType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(auth_types::PaymentAuthExchangeTokenType::get_headers( + self, req, connectors, + )?) + .body(auth_types::PaymentAuthExchangeTokenType::get_request_body( + self, req, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &auth_types::ExchangeTokenRouterData, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> { + let response: plaid::PlaidExchangeTokenResponse = res + .response + .parse_struct("PlaidExchangeTokenResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + <auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl auth_service::AuthServiceBankAccountCredentials for Plaid {} + +impl + ConnectorIntegration< + BankAccountCredentials, + auth_types::BankAccountCredentialsRequest, + auth_types::BankAccountCredentialsResponse, + > for Plaid +{ + fn get_headers( + &self, + req: &auth_types::BankDetailsRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &auth_types::BankDetailsRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<String, errors::ConnectorError> { + Ok(format!("{}{}", self.base_url(connectors), "/auth/get")) + } + + fn get_request_body( + &self, + req: &auth_types::BankDetailsRouterData, + ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> { + let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?; + let plaid_req = RequestBody::log_and_get_request_body( + &req_obj, + Encode::<plaid::PlaidBankAccountCredentialsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(plaid_req)) + } + + fn build_request( + &self, + req: &auth_types::BankDetailsRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&auth_types::PaymentAuthBankAccountDetailsType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers( + self, req, connectors, + )?) + .body(auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &auth_types::BankDetailsRouterData, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> { + let response: plaid::PlaidBankAccountCredentialsResponse = res + .response + .parse_struct("PlaidBankAccountCredentialsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + <auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs new file mode 100644 index 00000000000..5e1ad67aead --- /dev/null +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -0,0 +1,294 @@ +use std::collections::HashMap; + +use common_enums::PaymentMethodType; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{core::errors, types}; + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidLinkTokenRequest { + client_name: String, + country_codes: Vec<String>, + language: String, + products: Vec<String>, + user: User, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] + +pub struct User { + pub client_user_id: String, +} + +impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::LinkTokenRouterData) -> Result<Self, Self::Error> { + Ok(Self { + client_name: item.request.client_name.clone(), + country_codes: item.request.country_codes.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "country_codes", + }, + )?, + language: item.request.language.clone().unwrap_or("en".to_string()), + products: vec!["auth".to_string()], + user: User { + client_user_id: item.request.user_info.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "country_codes", + }, + )?, + }, + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidLinkTokenResponse { + link_token: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>> + for types::PaymentAuthRouterData<F, T, types::LinkTokenResponse> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::LinkTokenResponse { + link_token: item.response.link_token, + }), + ..item.data + }) + } +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidExchangeTokenRequest { + public_token: String, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] + +pub struct PlaidExchangeTokenResponse { + pub access_token: String, +} + +impl<F, T> + TryFrom< + types::ResponseRouterData<F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse>, + > for types::PaymentAuthRouterData<F, T, types::ExchangeTokenResponse> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PlaidExchangeTokenResponse, + T, + types::ExchangeTokenResponse, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::ExchangeTokenResponse { + access_token: item.response.access_token, + }), + ..item.data + }) + } +} + +impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::ExchangeTokenRouterData) -> Result<Self, Self::Error> { + Ok(Self { + public_token: item.request.public_token.clone(), + }) + } +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidBankAccountCredentialsRequest { + access_token: String, + options: Option<BankAccountCredentialsOptions>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] + +pub struct PlaidBankAccountCredentialsResponse { + pub accounts: Vec<PlaidBankAccountCredentialsAccounts>, + pub numbers: PlaidBankAccountCredentialsNumbers, + // pub item: PlaidBankAccountCredentialsItem, + pub request_id: String, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct BankAccountCredentialsOptions { + account_ids: Vec<String>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] + +pub struct PlaidBankAccountCredentialsAccounts { + pub account_id: String, + pub name: String, + pub subtype: Option<String>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsBalances { + pub available: Option<i32>, + pub current: Option<i32>, + pub limit: Option<i32>, + pub iso_currency_code: Option<String>, + pub unofficial_currency_code: Option<String>, + pub last_updated_datetime: Option<String>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsNumbers { + pub ach: Vec<PlaidBankAccountCredentialsACH>, + pub eft: Vec<PlaidBankAccountCredentialsEFT>, + pub international: Vec<PlaidBankAccountCredentialsInternational>, + pub bacs: Vec<PlaidBankAccountCredentialsBacs>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsItem { + pub item_id: String, + pub institution_id: Option<String>, + pub webhook: Option<String>, + pub error: Option<PlaidErrorResponse>, +} +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsACH { + pub account_id: String, + pub account: String, + pub routing: String, + pub wire_routing: Option<String>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsEFT { + pub account_id: String, + pub account: String, + pub institution: String, + pub branch: String, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsInternational { + pub account_id: String, + pub iban: String, + pub bic: String, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsBacs { + pub account_id: String, + pub account: String, + pub sort_code: String, +} + +impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> { + Ok(Self { + access_token: item.request.access_token.clone(), + options: item.request.optional_ids.as_ref().map(|bank_account_ids| { + BankAccountCredentialsOptions { + account_ids: bank_account_ids.ids.clone(), + } + }), + }) + } +} + +impl<F, T> + TryFrom< + types::ResponseRouterData< + F, + PlaidBankAccountCredentialsResponse, + T, + types::BankAccountCredentialsResponse, + >, + > for types::PaymentAuthRouterData<F, T, types::BankAccountCredentialsResponse> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PlaidBankAccountCredentialsResponse, + T, + types::BankAccountCredentialsResponse, + >, + ) -> Result<Self, Self::Error> { + let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts); + let mut bank_account_vec = Vec::new(); + let mut id_to_suptype = HashMap::new(); + + accounts_info.into_iter().for_each(|acc| { + id_to_suptype.insert(acc.account_id, (acc.subtype, acc.name)); + }); + + account_numbers.ach.into_iter().for_each(|ach| { + let (acc_type, acc_name) = + if let Some((_type, name)) = id_to_suptype.get(&ach.account_id) { + (_type.to_owned(), Some(name.clone())) + } else { + (None, None) + }; + + let bank_details_new = types::BankAccountDetails { + account_name: acc_name, + account_number: ach.account, + routing_number: ach.routing, + payment_method_type: PaymentMethodType::Ach, + account_id: ach.account_id, + account_type: acc_type, + }; + + bank_account_vec.push(bank_details_new); + }); + + Ok(Self { + response: Ok(types::BankAccountCredentialsResponse { + credentials: bank_account_vec, + }), + ..item.data + }) + } +} +pub struct PlaidAuthType { + pub client_id: Secret<String>, + pub secret: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self { + client_id: client_id.to_owned(), + secret: secret.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} + +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidErrorResponse { + pub display_message: Option<String>, + pub error_code: Option<String>, + pub error_message: String, + pub error_type: Option<String>, +} diff --git a/crates/pm_auth/src/consts.rs b/crates/pm_auth/src/consts.rs new file mode 100644 index 00000000000..dac3485ec8f --- /dev/null +++ b/crates/pm_auth/src/consts.rs @@ -0,0 +1,5 @@ +pub const REQUEST_TIME_OUT: u64 = 30; // will timeout after the mentioned limit +pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; // timeout error code +pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; // error message for timed out request +pub const NO_ERROR_CODE: &str = "No error code"; +pub const NO_ERROR_MESSAGE: &str = "No error message"; diff --git a/crates/pm_auth/src/core.rs b/crates/pm_auth/src/core.rs new file mode 100644 index 00000000000..629e98fbf87 --- /dev/null +++ b/crates/pm_auth/src/core.rs @@ -0,0 +1 @@ +pub mod errors; diff --git a/crates/pm_auth/src/core/errors.rs b/crates/pm_auth/src/core/errors.rs new file mode 100644 index 00000000000..31b178a6276 --- /dev/null +++ b/crates/pm_auth/src/core/errors.rs @@ -0,0 +1,27 @@ +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum ConnectorError { + #[error("Failed to obtain authentication type")] + FailedToObtainAuthType, + #[error("Missing required field: {field_name}")] + MissingRequiredField { field_name: &'static str }, + #[error("Failed to execute a processing step: {0:?}")] + ProcessingStepFailed(Option<bytes::Bytes>), + #[error("Failed to deserialize connector response")] + ResponseDeserializationFailed, + #[error("Failed to encode connector request")] + RequestEncodingFailed, +} + +pub type CustomResult<T, E> = error_stack::Result<T, E>; + +#[derive(Debug, thiserror::Error)] +pub enum ParsingError { + #[error("Failed to parse enum: {0}")] + EnumParseFailure(&'static str), + #[error("Failed to parse struct: {0}")] + StructParseFailure(&'static str), + #[error("Failed to serialize to {0} format")] + EncodeError(&'static str), + #[error("Unknown error while parsing")] + UnknownError, +} diff --git a/crates/pm_auth/src/lib.rs b/crates/pm_auth/src/lib.rs new file mode 100644 index 00000000000..60d0e06a1e0 --- /dev/null +++ b/crates/pm_auth/src/lib.rs @@ -0,0 +1,4 @@ +pub mod connector; +pub mod consts; +pub mod core; +pub mod types; diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs new file mode 100644 index 00000000000..6f5875247f1 --- /dev/null +++ b/crates/pm_auth/src/types.rs @@ -0,0 +1,152 @@ +pub mod api; + +use std::marker::PhantomData; + +use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}; +use common_enums::PaymentMethodType; +use masking::Secret; +#[derive(Debug, Clone)] +pub struct PaymentAuthRouterData<F, Request, Response> { + pub flow: PhantomData<F>, + pub merchant_id: Option<String>, + pub connector: Option<String>, + pub request: Request, + pub response: Result<Response, ErrorResponse>, + pub connector_auth_type: ConnectorAuthType, + pub connector_http_status_code: Option<u16>, +} + +#[derive(Debug, Clone)] +pub struct LinkTokenRequest { + pub client_name: String, + pub country_codes: Option<Vec<String>>, + pub language: Option<String>, + pub user_info: Option<String>, +} + +#[derive(Debug, Clone)] +pub struct LinkTokenResponse { + pub link_token: String, +} + +pub type LinkTokenRouterData = + PaymentAuthRouterData<LinkToken, LinkTokenRequest, LinkTokenResponse>; + +#[derive(Debug, Clone)] +pub struct ExchangeTokenRequest { + pub public_token: String, +} + +#[derive(Debug, Clone)] +pub struct ExchangeTokenResponse { + pub access_token: String, +} + +impl From<ExchangeTokenResponse> for api_models::pm_auth::ExchangeTokenCreateResponse { + fn from(value: ExchangeTokenResponse) -> Self { + Self { + access_token: value.access_token, + } + } +} + +pub type ExchangeTokenRouterData = + PaymentAuthRouterData<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; + +#[derive(Debug, Clone)] +pub struct BankAccountCredentialsRequest { + pub access_token: String, + pub optional_ids: Option<BankAccountOptionalIDs>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountOptionalIDs { + pub ids: Vec<String>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountCredentialsResponse { + pub credentials: Vec<BankAccountDetails>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountDetails { + pub account_name: Option<String>, + pub account_number: String, + pub routing_number: String, + pub payment_method_type: PaymentMethodType, + pub account_id: String, + pub account_type: Option<String>, +} + +pub type BankDetailsRouterData = PaymentAuthRouterData< + BankAccountCredentials, + BankAccountCredentialsRequest, + BankAccountCredentialsResponse, +>; + +pub type PaymentAuthLinkTokenType = + dyn self::api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>; + +pub type PaymentAuthExchangeTokenType = + dyn self::api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; + +pub type PaymentAuthBankAccountDetailsType = dyn self::api::ConnectorIntegration< + BankAccountCredentials, + BankAccountCredentialsRequest, + BankAccountCredentialsResponse, +>; + +#[derive(Clone, Debug, strum::EnumString, strum::Display)] +#[strum(serialize_all = "snake_case")] +pub enum PaymentMethodAuthConnectors { + Plaid, +} + +#[derive(Debug, Clone)] +pub struct ResponseRouterData<Flow, R, Request, Response> { + pub response: R, + pub data: PaymentAuthRouterData<Flow, Request, Response>, + pub http_code: u16, +} + +#[derive(Clone, Debug, serde::Serialize)] +pub struct ErrorResponse { + pub code: String, + pub message: String, + pub reason: Option<String>, + pub status_code: u16, +} + +impl ErrorResponse { + fn get_not_implemented() -> Self { + Self { + code: "IR_00".to_string(), + message: "This API is under development and will be made available soon.".to_string(), + reason: None, + status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), + } + } +} + +#[derive(Default, Debug, Clone, serde::Deserialize)] +pub enum ConnectorAuthType { + BodyKey { + client_id: Secret<String>, + secret: Secret<String>, + }, + #[default] + NoKey, +} + +#[derive(Clone, Debug)] +pub struct Response { + pub headers: Option<http::HeaderMap>, + pub response: bytes::Bytes, + pub status_code: u16, +} + +#[derive(serde::Deserialize, Clone)] +pub struct AuthServiceQueryParam { + pub client_secret: Option<String>, +} diff --git a/crates/pm_auth/src/types/api.rs b/crates/pm_auth/src/types/api.rs new file mode 100644 index 00000000000..2416d0fee1d --- /dev/null +++ b/crates/pm_auth/src/types/api.rs @@ -0,0 +1,167 @@ +pub mod auth_service; + +use std::fmt::Debug; + +use common_utils::{ + errors::CustomResult, + request::{Request, RequestBody}, +}; +use masking::Maskable; + +use crate::{ + core::errors::ConnectorError, + types::{self as auth_types, api::auth_service::AuthService}, +}; + +#[async_trait::async_trait] +pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync { + fn get_headers( + &self, + _req: &super::PaymentAuthRouterData<T, Req, Resp>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + Ok(vec![]) + } + + fn get_content_type(&self) -> &'static str { + mime::APPLICATION_JSON.essence_str() + } + + fn get_url( + &self, + _req: &super::PaymentAuthRouterData<T, Req, Resp>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> CustomResult<String, ConnectorError> { + Ok(String::new()) + } + + fn get_request_body( + &self, + _req: &super::PaymentAuthRouterData<T, Req, Resp>, + ) -> CustomResult<Option<RequestBody>, ConnectorError> { + Ok(None) + } + + fn build_request( + &self, + _req: &super::PaymentAuthRouterData<T, Req, Resp>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(None) + } + + fn handle_response( + &self, + data: &super::PaymentAuthRouterData<T, Req, Resp>, + _res: auth_types::Response, + ) -> CustomResult<super::PaymentAuthRouterData<T, Req, Resp>, ConnectorError> + where + T: Clone, + Req: Clone, + Resp: Clone, + { + Ok(data.clone()) + } + + fn get_error_response( + &self, + _res: auth_types::Response, + ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { + Ok(auth_types::ErrorResponse::get_not_implemented()) + } + + fn get_5xx_error_response( + &self, + res: auth_types::Response, + ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { + let error_message = match res.status_code { + 500 => "internal_server_error", + 501 => "not_implemented", + 502 => "bad_gateway", + 503 => "service_unavailable", + 504 => "gateway_timeout", + 505 => "http_version_not_supported", + 506 => "variant_also_negotiates", + 507 => "insufficient_storage", + 508 => "loop_detected", + 510 => "not_extended", + 511 => "network_authentication_required", + _ => "unknown_error", + }; + Ok(auth_types::ErrorResponse { + code: res.status_code.to_string(), + message: error_message.to_string(), + reason: String::from_utf8(res.response.to_vec()).ok(), + status_code: res.status_code, + }) + } +} + +pub trait ConnectorCommonExt<Flow, Req, Resp>: + ConnectorCommon + ConnectorIntegration<Flow, Req, Resp> +{ + fn build_headers( + &self, + _req: &auth_types::PaymentAuthRouterData<Flow, Req, Resp>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + Ok(Vec::new()) + } +} + +pub type BoxedConnectorIntegration<'a, T, Req, Resp> = + Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; + +pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { + fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; +} + +impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S +where + S: ConnectorIntegration<T, Req, Resp>, +{ + fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> { + Box::new(self) + } +} + +pub trait AuthServiceConnector: AuthService + Send + Debug {} + +impl<T: Send + Debug + AuthService> AuthServiceConnector for T {} + +pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>; + +#[derive(Clone, Debug)] +pub struct PaymentAuthConnectorData { + pub connector: BoxedPaymentAuthConnector, + pub connector_name: super::PaymentMethodAuthConnectors, +} + +pub trait ConnectorCommon { + fn id(&self) -> &'static str; + + fn get_auth_header( + &self, + _auth_type: &auth_types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + Ok(Vec::new()) + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str; + + fn build_error_response( + &self, + res: auth_types::Response, + ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { + Ok(auth_types::ErrorResponse { + status_code: res.status_code, + code: crate::consts::NO_ERROR_CODE.to_string(), + message: crate::consts::NO_ERROR_MESSAGE.to_string(), + reason: None, + }) + } +} diff --git a/crates/pm_auth/src/types/api/auth_service.rs b/crates/pm_auth/src/types/api/auth_service.rs new file mode 100644 index 00000000000..35d44970d51 --- /dev/null +++ b/crates/pm_auth/src/types/api/auth_service.rs @@ -0,0 +1,40 @@ +use crate::types::{ + BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest, + ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, +}; + +pub trait AuthService: + super::ConnectorCommon + + AuthServiceLinkToken + + AuthServiceExchangeToken + + AuthServiceBankAccountCredentials +{ +} + +#[derive(Debug, Clone)] +pub struct LinkToken; + +pub trait AuthServiceLinkToken: + super::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse> +{ +} + +#[derive(Debug, Clone)] +pub struct ExchangeToken; + +pub trait AuthServiceExchangeToken: + super::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse> +{ +} + +#[derive(Debug, Clone)] +pub struct BankAccountCredentials; + +pub trait AuthServiceBankAccountCredentials: + super::ConnectorIntegration< + BankAccountCredentials, + BankAccountCredentialsRequest, + BankAccountCredentialsResponse, +> +{ +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 791f617b30d..e498658e457 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -111,6 +111,7 @@ currency_conversion = { version = "0.1.0", path = "../currency_conversion" } data_models = { version = "0.1.0", path = "../data_models", default-features = false } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } +pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" } external_services = { version = "0.1.0", path = "../external_services" } kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" } masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 6cbffc186d2..0d098b9acab 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -100,6 +100,7 @@ pub struct Settings { pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub webhook_source_verification_call: WebhookSourceVerificationCall, + pub payment_method_auth: PaymentMethodAuth, pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig, #[cfg(feature = "payouts")] pub payouts: Payouts, @@ -154,6 +155,12 @@ pub struct ForexApi { pub redis_lock_timeout: u64, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct PaymentMethodAuth { + pub redis_expiry: i64, + pub pm_auth_key: String, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct DefaultExchangeRates { pub base_currency: String, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index be83de84916..0bd197ee22e 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -24,6 +24,7 @@ pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; +pub mod pm_auth; pub mod refunds; pub mod routing; pub mod surcharge_decision_config; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 5ab543d382f..113bc7d677d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -10,9 +10,10 @@ use common_utils::{ ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, pii, }; -use error_stack::{report, FutureExt, ResultExt}; +use error_stack::{report, FutureExt, IntoReport, ResultExt}; use futures::future::try_join_all; use masking::{PeekInterface, Secret}; +use pm_auth::connector::plaid::transformers::PlaidAuthType; use uuid::Uuid; use crate::{ @@ -762,7 +763,7 @@ pub async fn create_payment_connector( ) .await?; - let routable_connector = + let mut routable_connector = api_enums::RoutableConnectors::from_str(&req.connector_name.to_string()).ok(); let business_profile = state @@ -773,6 +774,30 @@ pub async fn create_payment_connector( id: profile_id.to_owned(), })?; + let pm_auth_connector = + api_enums::convert_pm_auth_connector(req.connector_name.to_string().as_str()); + + let is_unroutable_connector = if pm_auth_connector.is_some() { + if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid connector type given".to_string(), + }) + .into_report(); + } + true + } else { + let routable_connector_option = req + .connector_name + .to_string() + .parse() + .into_report() + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid connector name given".to_string(), + })?; + routable_connector = Some(routable_connector_option); + false + }; + // If connector label is not passed in the request, generate one let connector_label = req .connector_label @@ -877,6 +902,20 @@ pub async fn create_payment_connector( api_enums::ConnectorStatus::Active, )?; + if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth { + if let Some(val) = req.pm_auth_config.clone() { + validate_pm_auth( + val, + &*state.clone().store, + merchant_id.clone().as_str(), + &key_store, + merchant_account, + &Some(profile_id.clone()), + ) + .await?; + } + } + let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type, @@ -948,7 +987,7 @@ pub async fn create_payment_connector( #[cfg(feature = "connector_choice_mca_id")] merchant_connector_id: Some(mca.merchant_connector_id.clone()), #[cfg(not(feature = "connector_choice_mca_id"))] - sub_label: req.business_sub_label, + sub_label: req.business_sub_label.clone(), }; if !default_routing_config.contains(&choice) { @@ -956,7 +995,7 @@ pub async fn create_payment_connector( routing_helpers::update_merchant_default_config( &*state.store, merchant_id, - default_routing_config, + default_routing_config.clone(), ) .await?; } @@ -965,7 +1004,7 @@ pub async fn create_payment_connector( routing_helpers::update_merchant_default_config( &*state.store, &profile_id.clone(), - default_routing_config_for_profile, + default_routing_config_for_profile.clone(), ) .await?; } @@ -980,10 +1019,92 @@ pub async fn create_payment_connector( ], ); + if !is_unroutable_connector { + if let Some(routable_connector_val) = routable_connector { + let choice = routing_types::RoutableConnectorChoice { + #[cfg(feature = "backwards_compatibility")] + choice_kind: routing_types::RoutableChoiceKind::FullStruct, + connector: routable_connector_val, + #[cfg(feature = "connector_choice_mca_id")] + merchant_connector_id: Some(mca.merchant_connector_id.clone()), + #[cfg(not(feature = "connector_choice_mca_id"))] + sub_label: req.business_sub_label.clone(), + }; + + if !default_routing_config.contains(&choice) { + default_routing_config.push(choice.clone()); + routing_helpers::update_merchant_default_config( + &*state.clone().store, + merchant_id, + default_routing_config, + ) + .await?; + } + + if !default_routing_config_for_profile.contains(&choice) { + default_routing_config_for_profile.push(choice); + routing_helpers::update_merchant_default_config( + &*state.store, + &profile_id, + default_routing_config_for_profile, + ) + .await?; + } + } + }; + let mca_response = mca.try_into()?; Ok(service_api::ApplicationResponse::Json(mca_response)) } +async fn validate_pm_auth( + val: serde_json::Value, + db: &dyn StorageInterface, + merchant_id: &str, + key_store: &domain::MerchantKeyStore, + merchant_account: domain::MerchantAccount, + profile_id: &Option<String>, +) -> RouterResponse<()> { + let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(val) + .into_report() + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "invalid data received for payment method auth config".to_string(), + }) + .attach_printable("Failed to deserialize Payment Method Auth config")?; + + let all_mcas = db + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_id, + true, + key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_account.merchant_id.clone(), + })?; + + for conn_choice in config.enabled_payment_methods { + let pm_auth_mca = all_mcas + .clone() + .into_iter() + .find(|mca| mca.merchant_connector_id == conn_choice.mca_id) + .ok_or(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment method auth connector account not found".to_string(), + }) + .into_report()?; + + if &pm_auth_mca.profile_id != profile_id { + return Err(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment method auth profile_id differs from connector profile_id" + .to_string(), + }) + .into_report(); + } + } + + Ok(services::ApplicationResponse::StatusOk) +} + pub async fn retrieve_payment_connector( state: AppState, merchant_id: String, @@ -1066,7 +1187,7 @@ pub async fn update_payment_connector( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let _merchant_account = db + let merchant_account = db .find_merchant_account_by_merchant_id(merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1106,6 +1227,20 @@ pub async fn update_payment_connector( let (connector_status, disabled) = validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?; + if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth { + if let Some(val) = req.pm_auth_config.clone() { + validate_pm_auth( + val, + db, + merchant_id, + &key_store, + merchant_account, + &mca.profile_id, + ) + .await?; + } + } + let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: None, connector_type: Some(req.connector_type), @@ -1720,8 +1855,10 @@ pub(crate) fn validate_auth_and_metadata_type( signifyd::transformers::SignifydAuthType::try_from(val)?; Ok(()) } - api_enums::Connector::Plaid => Err(report!(errors::ConnectorError::InvalidConnectorName) - .attach_printable(format!("invalid connector name: {connector_name}"))), + api_enums::Connector::Plaid => { + PlaidAuthType::foreign_try_from(val)?; + Ok(()) + } } } diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index a2dbfb1480c..14a39f1d955 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -11,12 +11,12 @@ pub use api_models::{ pub use common_utils::request::RequestBody; use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; use diesel_models::enums; -use error_stack::IntoReport; use crate::{ core::{ - errors::{self, RouterResult}, + errors::RouterResult, payments::helpers, + pm_auth::{self as core_pm_auth}, }, routes::AppState, types::{ @@ -172,11 +172,14 @@ impl PaymentMethodRetrieve for Oss { .map(|card| Some((card, enums::PaymentMethod::Card))) } - storage::PaymentTokenData::AuthBankDebit(_) => { - Err(errors::ApiErrorResponse::NotImplemented { - message: errors::NotImplementedMessage::Default, - }) - .into_report() + storage::PaymentTokenData::AuthBankDebit(auth_token) => { + core_pm_auth::retrieve_payment_method_from_auth_service( + state, + merchant_key_store, + auth_token, + payment_intent, + ) + .await } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index bbcfe45a1d0..84aef952a53 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -13,6 +13,7 @@ use api_models::{ ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, + pm_auth::PaymentMethodAuthConfig, surcharge_decision_configs as api_surcharge_decision_configs, }; use common_utils::{ @@ -29,6 +30,8 @@ use super::surcharge_decision_configs::{ perform_surcharge_decision_management_for_payment_method_list, perform_surcharge_decision_management_for_saved_cards, }; +#[cfg(not(feature = "connector_choice_mca_id"))] +use crate::core::utils::get_connector_label; use crate::{ configs::settings, core::{ @@ -1081,9 +1084,9 @@ pub async fn list_payment_methods( logger::debug!(mca_before_filtering=?filtered_mcas); let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![]; - for mca in filtered_mcas { - let payment_methods = match mca.payment_methods_enabled { - Some(pm) => pm, + for mca in &filtered_mcas { + let payment_methods = match &mca.payment_methods_enabled { + Some(pm) => pm.clone(), None => continue, }; @@ -1094,13 +1097,15 @@ pub async fn list_payment_methods( payment_intent.as_ref(), payment_attempt.as_ref(), billing_address.as_ref(), - mca.connector_name, + mca.connector_name.clone(), pm_config_mapping, &state.conf.mandates.supported_payment_methods, ) .await?; } + let mut pmt_to_auth_connector = HashMap::new(); + if let Some((payment_attempt, payment_intent)) = payment_attempt.as_ref().zip(payment_intent.as_ref()) { @@ -1204,6 +1209,84 @@ pub async fn list_payment_methods( pre_routing_results.insert(pm_type, routable_choice); } + let redis_conn = db + .get_redis_conn() + .map_err(|redis_error| logger::error!(?redis_error)) + .ok(); + + let mut val = Vec::new(); + + for (payment_method_type, routable_connector_choice) in &pre_routing_results { + #[cfg(not(feature = "connector_choice_mca_id"))] + let connector_label = get_connector_label( + payment_intent.business_country, + payment_intent.business_label.as_ref(), + #[cfg(not(feature = "connector_choice_mca_id"))] + routable_connector_choice.sub_label.as_ref(), + #[cfg(feature = "connector_choice_mca_id")] + None, + routable_connector_choice.connector.to_string().as_str(), + ); + #[cfg(not(feature = "connector_choice_mca_id"))] + let matched_mca = filtered_mcas + .iter() + .find(|m| connector_label == m.connector_label); + + #[cfg(feature = "connector_choice_mca_id")] + let matched_mca = filtered_mcas.iter().find(|m| { + routable_connector_choice.merchant_connector_id.as_ref() + == Some(&m.merchant_connector_id) + }); + + if let Some(m) = matched_mca { + let pm_auth_config = m + .pm_auth_config + .as_ref() + .map(|config| { + serde_json::from_value::<PaymentMethodAuthConfig>(config.clone()) + .into_report() + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to deserialize Payment Method Auth config") + }) + .transpose() + .unwrap_or_else(|err| { + logger::error!(error=?err); + None + }); + + let matched_config = match pm_auth_config { + Some(config) => { + let internal_config = config + .enabled_payment_methods + .iter() + .find(|config| config.payment_method_type == *payment_method_type) + .cloned(); + + internal_config + } + None => None, + }; + + if let Some(config) = matched_config { + pmt_to_auth_connector + .insert(*payment_method_type, config.connector_name.clone()); + val.push(config); + } + } + } + + let pm_auth_key = format!("pm_auth_{}", payment_intent.payment_id); + let redis_expiry = state.conf.payment_method_auth.redis_expiry; + + if let Some(rc) = redis_conn { + rc.serialize_and_set_key_with_expiry(pm_auth_key.as_str(), val, redis_expiry) + .await + .attach_printable("Failed to store pm auth data in redis") + .unwrap_or_else(|err| { + logger::error!(error=?err); + }) + }; + routing_info.pre_routing_results = Some(pre_routing_results); let encoded = utils::Encode::<storage::PaymentRoutingInfo>::encode_to_value(&routing_info) @@ -1461,7 +1544,9 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector + .get(payment_method_types_hm.0) + .cloned(), }) } @@ -1496,7 +1581,9 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector + .get(payment_method_types_hm.0) + .cloned(), }) } @@ -1526,7 +1613,7 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), } }) } @@ -1559,7 +1646,7 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), } }) } @@ -1592,7 +1679,7 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), } }) } diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs new file mode 100644 index 00000000000..821f049d8cf --- /dev/null +++ b/crates/router/src/core/pm_auth.rs @@ -0,0 +1,729 @@ +use std::{collections::HashMap, str::FromStr}; + +use api_models::{ + enums, + payment_methods::{self, BankAccountAccessCreds}, + payments::{AddressDetails, BankDebitBilling, BankDebitData, PaymentMethodData}, +}; +use hex; +pub mod helpers; +pub mod transformers; + +use common_utils::{ + consts, + crypto::{HmacSha256, SignMessage}, + ext_traits::AsyncExt, + generate_id, +}; +use data_models::payments::PaymentIntent; +use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "kms")] +pub use external_services::kms; +use helpers::PaymentAuthConnectorDataExt; +use masking::{ExposeInterface, PeekInterface}; +use pm_auth::{ + connector::plaid::transformers::PlaidAuthType, + types::{ + self as pm_auth_types, + api::{ + auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}, + BoxedConnectorIntegration, PaymentAuthConnectorData, + }, + }, +}; + +use crate::{ + core::{ + errors::{self, ApiErrorResponse, RouterResponse, RouterResult, StorageErrorExt}, + payment_methods::cards, + payments::helpers as oss_helpers, + pm_auth::helpers::{self as pm_auth_helpers}, + }, + db::StorageInterface, + logger, + routes::AppState, + services::{ + pm_auth::{self as pm_auth_services}, + ApplicationResponse, + }, + types::{ + self, + domain::{self, types::decrypt}, + storage, + transformers::ForeignTryFrom, + }, +}; + +pub async fn create_link_token( + state: AppState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + payload: api_models::pm_auth::LinkTokenCreateRequest, +) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> { + let db = &*state.store; + + let redis_conn = db + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let pm_auth_key = format!("pm_auth_{}", payload.payment_id); + + let pm_auth_configs = redis_conn + .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( + pm_auth_key.as_str(), + "Vec<PaymentMethodAuthConnectorChoice>", + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get payment method auth choices from redis")?; + + let selected_config = pm_auth_configs + .into_iter() + .find(|config| { + config.payment_method == payload.payment_method + && config.payment_method_type == payload.payment_method_type + }) + .ok_or(ApiErrorResponse::GenericNotFoundError { + message: "payment method auth connector name not found".to_string(), + }) + .into_report()?; + + let connector_name = selected_config.connector_name.as_str(); + + let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?; + let connector_integration: BoxedConnectorIntegration< + '_, + LinkToken, + pm_auth_types::LinkTokenRequest, + pm_auth_types::LinkTokenResponse, + > = connector.connector.get_connector_integration(); + + let payment_intent = oss_helpers::verify_payment_intent_time_and_client_secret( + &*state.store, + &merchant_account, + payload.client_secret, + ) + .await?; + + let billing_country = payment_intent + .as_ref() + .async_map(|pi| async { + oss_helpers::get_address_by_id( + &*state.store, + pi.billing_address_id.clone(), + &key_store, + pi.payment_id.clone(), + merchant_account.merchant_id.clone(), + merchant_account.storage_scheme, + ) + .await + }) + .await + .transpose()? + .flatten() + .and_then(|address| address.country) + .map(|country| country.to_string()); + + let merchant_connector_account = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + merchant_account.merchant_id.as_str(), + &selected_config.mca_id, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_account.merchant_id.clone(), + })?; + + let auth_type = helpers::get_connector_auth_type(merchant_connector_account)?; + + let router_data = pm_auth_types::LinkTokenRouterData { + flow: std::marker::PhantomData, + merchant_id: Some(merchant_account.merchant_id), + connector: Some(connector_name.to_string()), + request: pm_auth_types::LinkTokenRequest { + client_name: "HyperSwitch".to_string(), + country_codes: Some(vec![billing_country.ok_or( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "billing_country", + }, + )?]), + language: payload.language, + user_info: payment_intent.and_then(|pi| pi.customer_id), + }, + response: Ok(pm_auth_types::LinkTokenResponse { + link_token: "".to_string(), + }), + connector_http_status_code: None, + connector_auth_type: auth_type, + }; + + let connector_resp = pm_auth_services::execute_connector_processing_step( + state.as_ref(), + connector_integration, + &router_data, + &connector.connector_name, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling link token creation connector api")?; + + let link_token_resp = + connector_resp + .response + .map_err(|err| ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: connector.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + })?; + + let response = api_models::pm_auth::LinkTokenCreateResponse { + link_token: link_token_resp.link_token, + connector: connector.connector_name.to_string(), + }; + + Ok(ApplicationResponse::Json(response)) +} + +impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType { + type Error = errors::ConnectorError; + + fn foreign_try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::BodyKey { api_key, key1 } => { + Ok::<Self, errors::ConnectorError>(Self { + client_id: api_key.to_owned(), + secret: key1.to_owned(), + }) + } + _ => Err(errors::ConnectorError::FailedToObtainAuthType), + } + } +} + +pub async fn exchange_token_core( + state: AppState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + payload: api_models::pm_auth::ExchangeTokenCreateRequest, +) -> RouterResponse<()> { + let db = &*state.store; + + let config = get_selected_config_from_redis(db, &payload).await?; + + let connector_name = config.connector_name.as_str(); + + let connector = + pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(connector_name)?; + + let merchant_connector_account = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + merchant_account.merchant_id.as_str(), + &config.mca_id, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_account.merchant_id.clone(), + })?; + + let auth_type = helpers::get_connector_auth_type(merchant_connector_account.clone())?; + + let access_token = get_access_token_from_exchange_api( + &connector, + connector_name, + &payload, + &auth_type, + &state, + ) + .await?; + + let bank_account_details_resp = get_bank_account_creds( + connector, + &merchant_account, + connector_name, + &access_token, + auth_type, + &state, + None, + ) + .await?; + + Box::pin(store_bank_details_in_payment_methods( + key_store, + payload, + merchant_account, + state, + bank_account_details_resp, + (connector_name, access_token), + merchant_connector_account.merchant_connector_id, + )) + .await?; + + Ok(ApplicationResponse::StatusOk) +} + +async fn store_bank_details_in_payment_methods( + key_store: domain::MerchantKeyStore, + payload: api_models::pm_auth::ExchangeTokenCreateRequest, + merchant_account: domain::MerchantAccount, + state: AppState, + bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse, + connector_details: (&str, String), + mca_id: String, +) -> RouterResult<()> { + let key = key_store.key.get_inner().peek(); + let db = &*state.clone().store; + let (connector_name, access_token) = connector_details; + + let payment_intent = db + .find_payment_intent_by_payment_id_merchant_id( + &payload.payment_id, + &merchant_account.merchant_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(ApiErrorResponse::PaymentNotFound)?; + + let customer_id = payment_intent + .customer_id + .ok_or(ApiErrorResponse::CustomerNotFound)?; + + let payment_methods = db + .find_payment_method_by_customer_id_merchant_id_list( + &customer_id, + &merchant_account.merchant_id, + ) + .await + .change_context(ApiErrorResponse::InternalServerError)?; + + let mut hash_to_payment_method: HashMap< + String, + ( + storage::PaymentMethod, + payment_methods::PaymentMethodDataBankCreds, + ), + > = HashMap::new(); + + for pm in payment_methods { + if pm.payment_method == enums::PaymentMethod::BankDebit { + let bank_details_pm_data = decrypt::<serde_json::Value, masking::WithType>( + pm.payment_method_data.clone(), + key, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt bank account details")? + .map(|x| x.into_inner().expose()) + .map(|v| { + serde_json::from_value::<payment_methods::PaymentMethodsData>(v) + .into_report() + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to deserialize Payment Method Auth config") + }) + .transpose() + .unwrap_or_else(|err| { + logger::error!(error=?err); + None + }) + .and_then(|pmd| match pmd { + payment_methods::PaymentMethodsData::BankDetails(bank_creds) => Some(bank_creds), + _ => None, + }) + .ok_or(ApiErrorResponse::InternalServerError)?; + + hash_to_payment_method.insert( + bank_details_pm_data.hash.clone(), + (pm, bank_details_pm_data), + ); + } + } + + #[cfg(feature = "kms")] + let pm_auth_key = kms::get_kms_client(&state.conf.kms) + .await + .decrypt(state.conf.payment_method_auth.pm_auth_key.clone()) + .await + .change_context(ApiErrorResponse::InternalServerError)?; + + #[cfg(not(feature = "kms"))] + let pm_auth_key = state.conf.payment_method_auth.pm_auth_key.clone(); + + let mut update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)> = + Vec::new(); + let mut new_entries: Vec<storage::PaymentMethodNew> = Vec::new(); + + for creds in bank_account_details_resp.credentials { + let hash_string = format!("{}-{}", creds.account_number, creds.routing_number); + let generated_hash = hex::encode( + HmacSha256::sign_message(&HmacSha256, pm_auth_key.as_bytes(), hash_string.as_bytes()) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to sign the message")?, + ); + + let contains_account = hash_to_payment_method.get(&generated_hash); + let mut pmd = payment_methods::PaymentMethodDataBankCreds { + mask: creds + .account_number + .chars() + .rev() + .take(4) + .collect::<String>() + .chars() + .rev() + .collect::<String>(), + hash: generated_hash, + account_type: creds.account_type, + account_name: creds.account_name, + payment_method_type: creds.payment_method_type, + connector_details: vec![payment_methods::BankAccountConnectorDetails { + connector: connector_name.to_string(), + mca_id: mca_id.clone(), + access_token: payment_methods::BankAccountAccessCreds::AccessToken( + access_token.clone(), + ), + account_id: creds.account_id, + }], + }; + + if let Some((pm, details)) = contains_account { + pmd.connector_details.extend( + details + .connector_details + .clone() + .into_iter() + .filter(|conn| conn.mca_id != mca_id), + ); + + let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); + let encrypted_data = + cards::create_encrypted_payment_method_data(&key_store, Some(payment_method_data)) + .await + .ok_or(ApiErrorResponse::InternalServerError)?; + let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: Some(encrypted_data), + }; + + update_entries.push((pm.clone(), pm_update)); + } else { + let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); + let encrypted_data = + cards::create_encrypted_payment_method_data(&key_store, Some(payment_method_data)) + .await + .ok_or(ApiErrorResponse::InternalServerError)?; + let pm_id = generate_id(consts::ID_LENGTH, "pm"); + let pm_new = storage::PaymentMethodNew { + customer_id: customer_id.clone(), + merchant_id: merchant_account.merchant_id.clone(), + payment_method_id: pm_id, + payment_method: enums::PaymentMethod::BankDebit, + payment_method_type: Some(creds.payment_method_type), + payment_method_issuer: None, + scheme: None, + metadata: None, + payment_method_data: Some(encrypted_data), + ..storage::PaymentMethodNew::default() + }; + + new_entries.push(pm_new); + }; + } + + store_in_db(update_entries, new_entries, db).await?; + + Ok(()) +} + +async fn store_in_db( + update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)>, + new_entries: Vec<storage::PaymentMethodNew>, + db: &dyn StorageInterface, +) -> RouterResult<()> { + let update_entries_futures = update_entries + .into_iter() + .map(|(pm, pm_update)| db.update_payment_method(pm, pm_update)) + .collect::<Vec<_>>(); + + let new_entries_futures = new_entries + .into_iter() + .map(|pm_new| db.insert_payment_method(pm_new)) + .collect::<Vec<_>>(); + + let update_futures = futures::future::join_all(update_entries_futures); + let new_futures = futures::future::join_all(new_entries_futures); + + let (update, new) = tokio::join!(update_futures, new_futures); + + let _ = update + .into_iter() + .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}"))); + + let _ = new + .into_iter() + .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}"))); + + Ok(()) +} + +pub async fn get_bank_account_creds( + connector: PaymentAuthConnectorData, + merchant_account: &domain::MerchantAccount, + connector_name: &str, + access_token: &str, + auth_type: pm_auth_types::ConnectorAuthType, + state: &AppState, + bank_account_id: Option<String>, +) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> { + let connector_integration_bank_details: BoxedConnectorIntegration< + '_, + BankAccountCredentials, + pm_auth_types::BankAccountCredentialsRequest, + pm_auth_types::BankAccountCredentialsResponse, + > = connector.connector.get_connector_integration(); + + let router_data_bank_details = pm_auth_types::BankDetailsRouterData { + flow: std::marker::PhantomData, + merchant_id: Some(merchant_account.merchant_id.clone()), + connector: Some(connector_name.to_string()), + request: pm_auth_types::BankAccountCredentialsRequest { + access_token: access_token.to_string(), + optional_ids: bank_account_id + .map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }), + }, + response: Ok(pm_auth_types::BankAccountCredentialsResponse { + credentials: Vec::new(), + }), + connector_http_status_code: None, + connector_auth_type: auth_type, + }; + + let bank_details_resp = pm_auth_services::execute_connector_processing_step( + state, + connector_integration_bank_details, + &router_data_bank_details, + &connector.connector_name, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling bank account details connector api")?; + + let bank_account_details_resp = + bank_details_resp + .response + .map_err(|err| ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: connector.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + })?; + + Ok(bank_account_details_resp) +} + +async fn get_access_token_from_exchange_api( + connector: &PaymentAuthConnectorData, + connector_name: &str, + payload: &api_models::pm_auth::ExchangeTokenCreateRequest, + auth_type: &pm_auth_types::ConnectorAuthType, + state: &AppState, +) -> RouterResult<String> { + let connector_integration: BoxedConnectorIntegration< + '_, + ExchangeToken, + pm_auth_types::ExchangeTokenRequest, + pm_auth_types::ExchangeTokenResponse, + > = connector.connector.get_connector_integration(); + + let router_data = pm_auth_types::ExchangeTokenRouterData { + flow: std::marker::PhantomData, + merchant_id: None, + connector: Some(connector_name.to_string()), + request: pm_auth_types::ExchangeTokenRequest { + public_token: payload.public_token.clone(), + }, + response: Ok(pm_auth_types::ExchangeTokenResponse { + access_token: "".to_string(), + }), + connector_http_status_code: None, + connector_auth_type: auth_type.clone(), + }; + + let resp = pm_auth_services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + &connector.connector_name, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling exchange token connector api")?; + + let exchange_token_resp = + resp.response + .map_err(|err| ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: connector.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + })?; + + let access_token = exchange_token_resp.access_token; + Ok(access_token) +} + +async fn get_selected_config_from_redis( + db: &dyn StorageInterface, + payload: &api_models::pm_auth::ExchangeTokenCreateRequest, +) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> { + let redis_conn = db + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let pm_auth_key = format!("pm_auth_{}", payload.payment_id); + + let pm_auth_configs = redis_conn + .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( + pm_auth_key.as_str(), + "Vec<PaymentMethodAuthConnectorChoice>", + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get payment method auth choices from redis")?; + + let selected_config = pm_auth_configs + .iter() + .find(|conf| { + conf.payment_method == payload.payment_method + && conf.payment_method_type == payload.payment_method_type + }) + .ok_or(ApiErrorResponse::GenericNotFoundError { + message: "connector name not found".to_string(), + }) + .into_report()? + .clone(); + + Ok(selected_config) +} + +pub async fn retrieve_payment_method_from_auth_service( + state: &AppState, + key_store: &domain::MerchantKeyStore, + auth_token: &payment_methods::BankAccountConnectorDetails, + payment_intent: &PaymentIntent, +) -> RouterResult<Option<(PaymentMethodData, enums::PaymentMethod)>> { + let db = state.store.as_ref(); + + let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( + auth_token.connector.as_str(), + )?; + + let merchant_account = db + .find_merchant_account_by_merchant_id(&payment_intent.merchant_id, key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let mca = db + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &payment_intent.merchant_id, + &auth_token.mca_id, + key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: auth_token.mca_id.clone(), + }) + .attach_printable( + "error while fetching merchant_connector_account from merchant_id and connector name", + )?; + + let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?; + + let BankAccountAccessCreds::AccessToken(access_token) = &auth_token.access_token; + + let bank_account_creds = get_bank_account_creds( + connector, + &merchant_account, + &auth_token.connector, + access_token, + auth_type, + state, + Some(auth_token.account_id.clone()), + ) + .await?; + + logger::debug!("bank_creds: {:?}", bank_account_creds); + + let bank_account = bank_account_creds + .credentials + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Bank account details not found")?; + + let mut bank_type = None; + if let Some(account_type) = bank_account.account_type.clone() { + bank_type = api_models::enums::BankType::from_str(account_type.as_str()) + .map_err(|error| logger::error!(%error,"unable to parse account_type {account_type:?}")) + .ok(); + } + + let address = oss_helpers::get_address_by_id( + &*state.store, + payment_intent.billing_address_id.clone(), + key_store, + payment_intent.payment_id.clone(), + merchant_account.merchant_id.clone(), + merchant_account.storage_scheme, + ) + .await?; + + let name = address + .as_ref() + .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner())); + + let address_details = address.clone().map(|addr| { + let line1 = addr.line1.map(|line1| line1.into_inner()); + let line2 = addr.line2.map(|line2| line2.into_inner()); + let line3 = addr.line3.map(|line3| line3.into_inner()); + let zip = addr.zip.map(|zip| zip.into_inner()); + let state = addr.state.map(|state| state.into_inner()); + let first_name = addr.first_name.map(|first_name| first_name.into_inner()); + let last_name = addr.last_name.map(|last_name| last_name.into_inner()); + + AddressDetails { + city: addr.city, + country: addr.country, + line1, + line2, + line3, + zip, + state, + first_name, + last_name, + } + }); + let payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { + billing_details: BankDebitBilling { + name: name.unwrap_or_default(), + email: common_utils::pii::Email::from(masking::Secret::new("".to_string())), + address: address_details, + }, + account_number: masking::Secret::new(bank_account.account_number.clone()), + routing_number: masking::Secret::new(bank_account.routing_number.clone()), + card_holder_name: None, + bank_account_holder_name: None, + bank_name: None, + bank_type, + bank_holder_type: None, + }); + + Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit))) +} diff --git a/crates/router/src/core/pm_auth/helpers.rs b/crates/router/src/core/pm_auth/helpers.rs new file mode 100644 index 00000000000..43d30705a80 --- /dev/null +++ b/crates/router/src/core/pm_auth/helpers.rs @@ -0,0 +1,33 @@ +use common_utils::ext_traits::ValueExt; +use error_stack::{IntoReport, ResultExt}; +use pm_auth::types::{self as pm_auth_types, api::BoxedPaymentAuthConnector}; + +use crate::{ + core::errors::{self, ApiErrorResponse}, + types::{self, domain, transformers::ForeignTryFrom}, +}; + +pub trait PaymentAuthConnectorDataExt { + fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse> + where + Self: Sized; + fn convert_connector( + connector_name: pm_auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse>; +} + +pub fn get_connector_auth_type( + merchant_connector_account: domain::MerchantConnectorAccount, +) -> errors::CustomResult<pm_auth_types::ConnectorAuthType, ApiErrorResponse> { + let auth_type: types::ConnectorAuthType = merchant_connector_account + .connector_account_details + .parse_value("ConnectorAuthType") + .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound { + id: "ConnectorAuthType".to_string(), + })?; + + pm_auth_types::ConnectorAuthType::foreign_try_from(auth_type) + .into_report() + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while converting ConnectorAuthType") +} diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs new file mode 100644 index 00000000000..8a1369c2e02 --- /dev/null +++ b/crates/router/src/core/pm_auth/transformers.rs @@ -0,0 +1,18 @@ +use pm_auth::types::{self as pm_auth_types}; + +use crate::{core::errors, types, types::transformers::ForeignTryFrom}; + +impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType { + type Error = errors::ConnectorError; + fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::BodyKey { api_key, key1 } => { + Ok::<Self, errors::ConnectorError>(Self::BodyKey { + client_id: api_key.to_owned(), + secret: key1.to_owned(), + }) + } + _ => Err(errors::ConnectorError::FailedToObtainAuthType), + } + } +} diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index ce1717c9e93..ec718b2dde9 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -40,6 +40,8 @@ pub mod verify_connector; pub mod webhooks; pub mod locker_migration; +#[cfg(any(feature = "olap", feature = "oltp"))] +pub mod pm_auth; #[cfg(feature = "dummy_connector")] pub use self::app::DummyConnector; #[cfg(any(feature = "olap", feature = "oltp"))] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6b72e69b9f4..a7c394b7b6c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -20,6 +20,8 @@ use super::currency; use super::dummy_connector::*; #[cfg(feature = "payouts")] use super::payouts::*; +#[cfg(feature = "oltp")] +use super::pm_auth; #[cfg(feature = "olap")] use super::routing as cloud_routing; #[cfg(all(feature = "olap", feature = "kms"))] @@ -555,6 +557,8 @@ impl PaymentMethods { .route(web::post().to(payment_method_update_api)) .route(web::delete().to(payment_method_delete_api)), ) + .service(web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create))) + .service(web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token))) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 88c35bb0a13..533d1d3a629 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -13,6 +13,7 @@ pub enum ApiIdentifier { Ephemeral, Mandates, PaymentMethods, + PaymentMethodAuth, Payouts, Disputes, CardsInfo, @@ -86,6 +87,8 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentMethodsDelete | Flow::ValidatePaymentMethod => Self::PaymentMethods, + Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth, + Flow::PaymentsCreate | Flow::PaymentsRetrieve | Flow::PaymentsUpdate diff --git a/crates/router/src/routes/pm_auth.rs b/crates/router/src/routes/pm_auth.rs new file mode 100644 index 00000000000..cfadd787c31 --- /dev/null +++ b/crates/router/src/routes/pm_auth.rs @@ -0,0 +1,73 @@ +use actix_web::{web, HttpRequest, Responder}; +use api_models as api_types; +use router_env::{instrument, tracing, types::Flow}; + +use crate::{core::api_locking, routes::AppState, services::api as oss_api}; + +#[instrument(skip_all, fields(flow = ?Flow::PmAuthLinkTokenCreate))] +pub async fn link_token_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_types::pm_auth::LinkTokenCreateRequest>, +) -> impl Responder { + let payload = json_payload.into_inner(); + let flow = Flow::PmAuthLinkTokenCreate; + let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth( + req.headers(), + &payload, + ) { + Ok((auth, _auth_flow)) => (auth, _auth_flow), + Err(e) => return oss_api::log_and_return_error_response(e), + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, payload| { + crate::core::pm_auth::create_link_token( + state, + auth.merchant_account, + auth.key_store, + payload, + ) + }, + &*auth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[instrument(skip_all, fields(flow = ?Flow::PmAuthExchangeToken))] +pub async fn exchange_token( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_types::pm_auth::ExchangeTokenCreateRequest>, +) -> impl Responder { + let payload = json_payload.into_inner(); + let flow = Flow::PmAuthExchangeToken; + let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth( + req.headers(), + &payload, + ) { + Ok((auth, _auth_flow)) => (auth, _auth_flow), + Err(e) => return oss_api::log_and_return_error_response(e), + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, payload| { + crate::core::pm_auth::exchange_token_core( + state, + auth.merchant_account, + auth.key_store, + payload, + ) + }, + &*auth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index e46612b95df..57f3b802bd5 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -6,6 +6,7 @@ pub mod encryption; pub mod jwt; pub mod kafka; pub mod logger; +pub mod pm_auth; #[cfg(feature = "email")] pub mod email; diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 8a0cd7c729e..b48465ebd17 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -641,6 +641,18 @@ impl ClientSecretFetch for api_models::payments::RetrievePaymentLinkRequest { } } +impl ClientSecretFetch for api_models::pm_auth::LinkTokenCreateRequest { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref() + } +} + +impl ClientSecretFetch for api_models::pm_auth::ExchangeTokenCreateRequest { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref() + } +} + pub fn get_auth_type_and_flow<A: AppStateInfo + Sync>( headers: &HeaderMap, ) -> RouterResult<( diff --git a/crates/router/src/services/pm_auth.rs b/crates/router/src/services/pm_auth.rs new file mode 100644 index 00000000000..7487b12663b --- /dev/null +++ b/crates/router/src/services/pm_auth.rs @@ -0,0 +1,95 @@ +use pm_auth::{ + consts, + core::errors::ConnectorError, + types::{self as pm_auth_types, api::BoxedConnectorIntegration, PaymentAuthRouterData}, +}; + +use crate::{ + core::errors::{self}, + logger, + routes::AppState, + services::{self}, +}; + +pub async fn execute_connector_processing_step< + 'b, + 'a, + T: 'static, + Req: Clone + 'static, + Resp: Clone + 'static, +>( + state: &'b AppState, + connector_integration: BoxedConnectorIntegration<'a, T, Req, Resp>, + req: &'b PaymentAuthRouterData<T, Req, Resp>, + connector: &pm_auth_types::PaymentMethodAuthConnectors, +) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError> +where + T: Clone, + Req: Clone, + Resp: Clone, +{ + let mut router_data = req.clone(); + + let connector_request = connector_integration.build_request(req, connector)?; + + match connector_request { + Some(request) => { + logger::debug!(connector_request=?request); + let response = services::api::call_connector_api(state, request).await; + logger::debug!(connector_response=?response); + match response { + Ok(body) => { + let response = match body { + Ok(body) => { + let body = pm_auth_types::Response { + headers: body.headers, + response: body.response, + status_code: body.status_code, + }; + let connector_http_status_code = Some(body.status_code); + let mut data = + connector_integration.handle_response(&router_data, body)?; + data.connector_http_status_code = connector_http_status_code; + + data + } + Err(body) => { + let body = pm_auth_types::Response { + headers: body.headers, + response: body.response, + status_code: body.status_code, + }; + router_data.connector_http_status_code = Some(body.status_code); + + let error = match body.status_code { + 500..=511 => connector_integration.get_5xx_error_response(body)?, + _ => connector_integration.get_error_response(body)?, + }; + + router_data.response = Err(error); + + router_data + } + }; + Ok(response) + } + Err(error) => { + if error.current_context().is_upstream_timeout() { + let error_response = pm_auth_types::ErrorResponse { + code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), + message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), + reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), + status_code: 504, + }; + router_data.response = Err(error_response); + router_data.connector_http_status_code = Some(504); + Ok(router_data) + } else { + Err(error.change_context(ConnectorError::ProcessingStepFailed(None))) + } + } + } + } + None => Ok(router_data), + } +} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index de28c1a3188..aa563c647ea 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -10,6 +10,8 @@ pub mod api; pub mod domain; #[cfg(feature = "frm")] pub mod fraud_check; +pub mod pm_auth; + pub mod storage; pub mod transformers; diff --git a/crates/router/src/types/pm_auth.rs b/crates/router/src/types/pm_auth.rs new file mode 100644 index 00000000000..e2d08c6afea --- /dev/null +++ b/crates/router/src/types/pm_auth.rs @@ -0,0 +1,38 @@ +use std::str::FromStr; + +use error_stack::{IntoReport, ResultExt}; +use pm_auth::{ + connector::plaid, + types::{ + self as pm_auth_types, + api::{BoxedPaymentAuthConnector, PaymentAuthConnectorData}, + }, +}; + +use crate::core::{ + errors::{self, ApiErrorResponse}, + pm_auth::helpers::PaymentAuthConnectorDataExt, +}; + +impl PaymentAuthConnectorDataExt for PaymentAuthConnectorData { + fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse> { + let connector_name = pm_auth_types::PaymentMethodAuthConnectors::from_str(name) + .into_report() + .change_context(ApiErrorResponse::IncorrectConnectorNameGiven) + .attach_printable_lazy(|| { + format!("unable to parse connector: {:?}", name.to_string()) + })?; + let connector = Self::convert_connector(connector_name.clone())?; + Ok(Self { + connector, + connector_name, + }) + } + fn convert_connector( + connector_name: pm_auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse> { + match connector_name { + pm_auth_types::PaymentMethodAuthConnectors::Plaid => Ok(Box::new(&plaid::Plaid)), + } + } +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 13ca344e9c5..b682bcb12e6 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -295,6 +295,10 @@ pub enum Flow { UserMerchantAccountList, /// Get users for merchant account GetUserDetails, + /// PaymentMethodAuth Link token create + PmAuthLinkTokenCreate, + /// PaymentMethodAuth Exchange token create + PmAuthExchangeToken, /// Get reset password link ForgotPassword, /// Reset password using link
2023-12-04T10:10:25Z
## 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 --> PM Auth service migration ### 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). --> ## 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 merchant account - ``` curl --location --request POST 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1701764398", "locker_id": "m0010", "merchant_name": "Sarthak", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` 2. Create API key 3. Create Plaid Connector account ``` curl --location --request POST 'http://localhost:8080/account/merchant_1701763754/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "payment_method_auth", "connector_name": "plaid", "connector_account_details": { "auth_type": "BodyKey", "api_key": "some key", "key1": "some key" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label":"default", "status": "active", "metadata": { "city": "NY", "unit": "245" } }' ``` 4. Create payment connector account - ``` curl --location --request POST 'http://localhost:8080/account/merchant_1701763754/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "some key" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default", "pm_auth_config": { "enabled_payment_methods": [ { "payment_method": "bank_debit", "payment_method_type": "ach", "connector_name": "plaid", "mca_id": "mca_F6MPzhuQvzhHhOsVdgxi" } ] } }' ``` 5. Payments create - ``` curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O08Uv8O5PjAfrxsSLuduC1bn3FTWEpk0N2vvAKnvhAfc7jISAnrNgkTtcbibjO00' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 6. List PM for merchant - ``` curl --location --request GET 'http://localhost:8080/account/payment_methods?client_secret=pay_57JSBXgwKCHdgIyvLXDi_secret_1arVvWIGuP7XlWPMrt8W' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_588a676d99f8470ca0eb3a6d5b955f2a' \ --data-raw '' ``` 7. Link token API - ``` curl --location --request POST 'http://localhost:8080/payment_methods/auth/link' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_588a676d99f8470ca0eb3a6d5b955f2a' \ --data-raw '{ "client_secret": "pay_57JSBXgwKCHdgIyvLXDi_secret_1arVvWIGuP7XlWPMrt8W", "payment_id": "pay_57JSBXgwKCHdgIyvLXDi", "payment_method": "bank_debit", "payment_method_type": "ach" }' ``` 8. Get public token from plaid - ``` curl --location --request POST 'https://sandbox.plaid.com/sandbox/public_token/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_O08Uv8O5PjAfrxsSLuduC1bn3FTWEpk0N2vvAKnvhAfc7jISAnrNgkTtcbibjO00' \ --data-raw '{ "client_id": "some key", "secret": "some key", "institution_id": "ins_20", "initial_products": [ "auth" ], "options": { "webhook": "https://www.genericwebhookurl.com/webhook" } }' ``` 9. Exchange token API - ``` curl --location --request POST 'http://localhost:8080/payment_methods/auth/exchange' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_588a676d99f8470ca0eb3a6d5b955f2a' \ --data-raw '{ "client_secret": "pay_57JSBXgwKCHdgIyvLXDi_secret_1arVvWIGuP7XlWPMrt8W", "public_token": "public-sandbox-19e07c9f-8b96-4e96-81a1-e3e3d5c70dc6", "payment_id": "pay_57JSBXgwKCHdgIyvLXDi", "payment_method": "bank_debit", "payment_method_type": "ach" }' ``` 10. Pm list for customer (take any payment token) - ``` curl --location --request GET 'http://localhost:8080/customers/StripeCustomer/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_O08Uv8O5PjAfrxsSLuduC1bn3FTWEpk0N2vvAKnvhAfc7jISAnrNgkTtcbibjO00' ``` 11. Payments confirm with payment_token - ``` curl --location --request POST 'http://localhost:8080/payments/pay_57JSBXgwKCHdgIyvLXDi/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O08Uv8O5PjAfrxsSLuduC1bn3FTWEpk0N2vvAKnvhAfc7jISAnrNgkTtcbibjO00' \ --data-raw '{ "payment_method": "bank_debit", "payment_method_type": "ach", "payment_token": "token_2OqGjTK08Gen3iTEJq6u" }' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cfafd5cd29857283d57731dda7c5a332a493f531
juspay/hyperswitch
juspay__hyperswitch-3070
Bug: [FEATURE] Make the Euclid Knowledge Graph generic in its supported keys & values ### Feature Description The Euclid Knowledge Graph is a framework that allows the developer to model domain specific constraints in routing, including but not limited to, general payment domain constraints (e.g.: the payment method should be card for the card type to be debit), merchant-specific constraints (e.g: Applepay is enabled for Stripe but not for Trustpay), etc. Currently the Knowledge Graph has a hard and fast dependency on the `DirValue` for modeling its constraints, which is the primary Domain Intermediate Representation type used by the Euclid Rule Engine. This causes anyone who wants to use the knowledge graph for purposes other than routing to depend on the routing module. We want to separate out the Knowledge Graph from routing and convert it into a more generic **_Constraint Graph_**. ### Possible Implementation Pull out the Knowledge Graph from Euclid into its own `constraint_graph` crate, and make the Key and Value types in the constraints generic, with the implementation having certain trait bounds on the generic types as per requirement. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index 00c491d7101..7fce1e7f538 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2677,6 +2677,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" +[[package]] +name = "erased-serde" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c138974f9d5e7fe373eb04df7cae98833802ae4b11c24ac7039a21d5af4b26c" +dependencies = [ + "serde", +] + [[package]] name = "erased-serde" version = "0.4.4" @@ -2733,10 +2742,11 @@ version = "0.1.0" dependencies = [ "common_enums", "criterion", - "erased-serde", + "erased-serde 0.4.4", "euclid_macros", "frunk", "frunk_core", + "hyperswitch_constraint_graph", "nom", "once_cell", "rustc-hash", @@ -2768,6 +2778,7 @@ dependencies = [ "currency_conversion", "euclid", "getrandom", + "hyperswitch_constraint_graph", "kgraph_utils", "once_cell", "ron-parser", @@ -3602,6 +3613,18 @@ dependencies = [ "tokio 1.37.0", ] +[[package]] +name = "hyperswitch_constraint_graph" +version = "0.1.0" +dependencies = [ + "erased-serde 0.3.31", + "rustc-hash", + "serde", + "serde_json", + "strum 0.25.0", + "thiserror", +] + [[package]] name = "hyperswitch_domain_models" version = "0.1.0" @@ -3911,6 +3934,7 @@ dependencies = [ "common_enums", "criterion", "euclid", + "hyperswitch_constraint_graph", "masking", "serde", "serde_json", @@ -4067,7 +4091,7 @@ version = "0.1.0" dependencies = [ "bytes 1.6.0", "diesel", - "erased-serde", + "erased-serde 0.4.4", "serde", "serde_json", "subtle", @@ -5599,7 +5623,7 @@ dependencies = [ "digest", "dyn-clone", "encoding_rs", - "erased-serde", + "erased-serde 0.4.4", "error-stack", "euclid", "events", @@ -5608,6 +5632,7 @@ dependencies = [ "hex", "http 0.2.12", "hyper 0.14.28", + "hyperswitch_constraint_graph", "hyperswitch_domain_models", "hyperswitch_interfaces", "image", @@ -6698,6 +6723,15 @@ dependencies = [ "strum_macros 0.24.3", ] +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +dependencies = [ + "strum_macros 0.25.3", +] + [[package]] name = "strum" version = "0.26.2" @@ -6720,6 +6754,19 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "strum_macros" +version = "0.25.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.57", +] + [[package]] name = "strum_macros" version = "0.26.2" diff --git a/crates/euclid/Cargo.toml b/crates/euclid/Cargo.toml index 7de27645523..3341746ab74 100644 --- a/crates/euclid/Cargo.toml +++ b/crates/euclid/Cargo.toml @@ -21,6 +21,7 @@ utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order # First party dependencies common_enums = { version = "0.1.0", path = "../common_enums" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } euclid_macros = { version = "0.1.0", path = "../euclid_macros" } [features] diff --git a/crates/euclid/src/dssa/analyzer.rs b/crates/euclid/src/dssa/analyzer.rs index 4c615e78495..dc1da99a832 100644 --- a/crates/euclid/src/dssa/analyzer.rs +++ b/crates/euclid/src/dssa/analyzer.rs @@ -4,11 +4,15 @@ //! in the Euclid Rule DSL. These include standard control flow analyses like testing //! conflicting assertions, to Domain Specific Analyses making use of the //! [`Knowledge Graph Framework`](crate::dssa::graph). +use hyperswitch_constraint_graph::{ConstraintGraph, Memoization}; use rustc_hash::{FxHashMap, FxHashSet}; -use super::{graph::Memoization, types::EuclidAnalysable}; use crate::{ - dssa::{graph, state_machine, truth, types}, + dssa::{ + graph::CgraphExt, + state_machine, truth, + types::{self, EuclidAnalysable}, + }, frontend::{ ast, dir::{self, EuclidDirFilter}, @@ -203,12 +207,12 @@ fn perform_condition_analyses( fn perform_context_analyses( context: &types::ConjunctiveContext<'_>, - knowledge_graph: &graph::KnowledgeGraph<'_>, + knowledge_graph: &ConstraintGraph<'_, dir::DirValue>, ) -> Result<(), types::AnalysisError> { perform_condition_analyses(context)?; let mut memo = Memoization::new(); knowledge_graph - .perform_context_analysis(context, &mut memo) + .perform_context_analysis(context, &mut memo, None) .map_err(|err| types::AnalysisError { error_type: types::AnalysisErrorType::GraphAnalysis(err, memo), metadata: Default::default(), @@ -218,7 +222,7 @@ fn perform_context_analyses( pub fn analyze<O: EuclidAnalysable + EuclidDirFilter>( program: ast::Program<O>, - knowledge_graph: Option<&graph::KnowledgeGraph<'_>>, + knowledge_graph: Option<&ConstraintGraph<'_, dir::DirValue>>, ) -> Result<vir::ValuedProgram<O>, types::AnalysisError> { let dir_program = ast::lowering::lower_program(program)?; @@ -241,9 +245,14 @@ mod tests { use std::{ops::Deref, sync::Weak}; use euclid_macros::knowledge; + use hyperswitch_constraint_graph as cgraph; use super::*; - use crate::{dirval, types::DummyOutput}; + use crate::{ + dirval, + dssa::graph::{self, euclid_graph_prelude}, + types::DummyOutput, + }; #[test] fn test_conflicting_assertion_detection() { @@ -368,7 +377,7 @@ mod tests { #[test] fn test_negation_graph_analysis() { - let graph = knowledge! {crate + let graph = knowledge! { CaptureMethod(Automatic) ->> PaymentMethod(Card); }; @@ -410,18 +419,18 @@ mod tests { .deref() .clone() { - graph::AnalysisTrace::Value { predecessors, .. } => { - let _value = graph::NodeValue::Value(dir::DirValue::PaymentMethod( + cgraph::AnalysisTrace::Value { predecessors, .. } => { + let _value = cgraph::NodeValue::Value(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )); - let _relation = graph::Relation::Positive; + let _relation = cgraph::Relation::Positive; predecessors } _ => panic!("Expected Negation Trace for payment method = card"), }; let pred = match predecessor { - Some(graph::ValueTracePredecessor::Mandatory(predecessor)) => predecessor, + Some(cgraph::error::ValueTracePredecessor::Mandatory(predecessor)) => predecessor, _ => panic!("No predecessor found"), }; assert_eq!( @@ -433,11 +442,11 @@ mod tests { *Weak::upgrade(&pred) .expect("Expected Arc not found") .deref(), - graph::AnalysisTrace::Value { - value: graph::NodeValue::Value(dir::DirValue::CaptureMethod( + cgraph::AnalysisTrace::Value { + value: cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( dir::enums::CaptureMethod::Automatic )), - relation: graph::Relation::Positive, + relation: cgraph::Relation::Positive, info: None, metadata: None, predecessors: None, diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index cb72cca0448..526248a3817 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -1,272 +1,53 @@ -use std::{ - fmt::Debug, - hash::Hash, - ops::{Deref, DerefMut}, - sync::{Arc, Weak}, -}; +use std::{fmt::Debug, sync::Weak}; -use erased_serde::{self, Serialize as ErasedSerialize}; +use hyperswitch_constraint_graph as cgraph; use rustc_hash::{FxHashMap, FxHashSet}; -use serde::Serialize; use crate::{ dssa::types, frontend::dir, types::{DataType, Metadata}, - utils, }; -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Hash, strum::Display)] -pub enum Strength { - Weak, - Normal, - Strong, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum Relation { - Positive, - Negative, -} - -impl From<Relation> for bool { - fn from(value: Relation) -> Self { - matches!(value, Relation::Positive) - } -} - -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Hash)] -pub struct NodeId(usize); - -impl utils::EntityId for NodeId { - #[inline] - fn get_id(&self) -> usize { - self.0 - } - - #[inline] - fn with_id(id: usize) -> Self { - Self(id) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct DomainInfo<'a> { - pub domain_identifier: DomainIdentifier<'a>, - pub domain_description: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct DomainIdentifier<'a>(&'a str); - -impl<'a> DomainIdentifier<'a> { - pub fn new(domain_identifier: &'a str) -> Self { - Self(domain_identifier) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct DomainId(usize); - -impl utils::EntityId for DomainId { - #[inline] - fn get_id(&self) -> usize { - self.0 - } - - #[inline] - fn with_id(id: usize) -> Self { - Self(id) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct EdgeId(usize); +pub mod euclid_graph_prelude { + pub use hyperswitch_constraint_graph as cgraph; + pub use rustc_hash::{FxHashMap, FxHashSet}; -impl utils::EntityId for EdgeId { - #[inline] - fn get_id(&self) -> usize { - self.0 - } - - #[inline] - fn with_id(id: usize) -> Self { - Self(id) - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct Memoization(FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace>>>); - -impl Memoization { - pub fn new() -> Self { - Self(FxHashMap::default()) - } -} - -impl Default for Memoization { - #[inline] - fn default() -> Self { - Self::new() - } -} - -impl Deref for Memoization { - type Target = FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace>>>; - fn deref(&self) -> &Self::Target { - &self.0 - } -} -impl DerefMut for Memoization { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} -#[derive(Debug, Clone)] -pub struct Edge { - pub strength: Strength, - pub relation: Relation, - pub pred: NodeId, - pub succ: NodeId, + pub use crate::{ + dssa::graph::*, + frontend::dir::{enums::*, DirKey, DirKeyKind, DirValue}, + types::*, + }; } -#[derive(Debug)] -pub struct Node { - pub node_type: NodeType, - pub preds: Vec<EdgeId>, - pub succs: Vec<EdgeId>, - pub domain_ids: Vec<DomainId>, -} +impl cgraph::KeyNode for dir::DirKey {} -impl Node { - fn new(node_type: NodeType, domain_ids: Vec<DomainId>) -> Self { - Self { - node_type, - preds: Vec::new(), - succs: Vec::new(), - domain_ids, - } - } -} - -pub trait KgraphMetadata: ErasedSerialize + std::any::Any + Sync + Send + Debug {} -erased_serde::serialize_trait_object!(KgraphMetadata); - -impl<M> KgraphMetadata for M where M: ErasedSerialize + std::any::Any + Sync + Send + Debug {} - -#[derive(Debug)] -pub struct KnowledgeGraph<'a> { - domain: utils::DenseMap<DomainId, DomainInfo<'a>>, - nodes: utils::DenseMap<NodeId, Node>, - edges: utils::DenseMap<EdgeId, Edge>, - value_map: FxHashMap<NodeValue, NodeId>, - node_info: utils::DenseMap<NodeId, Option<&'static str>>, - node_metadata: utils::DenseMap<NodeId, Option<Arc<dyn KgraphMetadata>>>, -} - -pub struct KnowledgeGraphBuilder<'a> { - domain: utils::DenseMap<DomainId, DomainInfo<'a>>, - nodes: utils::DenseMap<NodeId, Node>, - edges: utils::DenseMap<EdgeId, Edge>, - domain_identifier_map: FxHashMap<DomainIdentifier<'a>, DomainId>, - value_map: FxHashMap<NodeValue, NodeId>, - edges_map: FxHashMap<(NodeId, NodeId), EdgeId>, - node_info: utils::DenseMap<NodeId, Option<&'static str>>, - node_metadata: utils::DenseMap<NodeId, Option<Arc<dyn KgraphMetadata>>>, -} +impl cgraph::ValueNode for dir::DirValue { + type Key = dir::DirKey; -impl<'a> Default for KnowledgeGraphBuilder<'a> { - #[inline] - fn default() -> Self { - Self::new() + fn get_key(&self) -> Self::Key { + Self::get_key(self) } } -#[derive(Debug, PartialEq, Eq)] -pub enum NodeType { - AllAggregator, - AnyAggregator, - InAggregator(FxHashSet<dir::DirValue>), - Value(NodeValue), -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)] -#[serde(tag = "type", content = "value", rename_all = "snake_case")] -pub enum NodeValue { - Key(dir::DirKey), - Value(dir::DirValue), -} - -impl From<dir::DirValue> for NodeValue { - fn from(value: dir::DirValue) -> Self { - Self::Value(value) - } -} - -impl From<dir::DirKey> for NodeValue { - fn from(key: dir::DirKey) -> Self { - Self::Key(key) - } -} - -#[derive(Debug, Clone, serde::Serialize)] -#[serde(tag = "type", content = "predecessor", rename_all = "snake_case")] -pub enum ValueTracePredecessor { - Mandatory(Box<Weak<AnalysisTrace>>), - OneOf(Vec<Weak<AnalysisTrace>>), -} - -#[derive(Debug, Clone, serde::Serialize)] -#[serde(tag = "type", content = "trace", rename_all = "snake_case")] -pub enum AnalysisTrace { - Value { - value: NodeValue, - relation: Relation, - predecessors: Option<ValueTracePredecessor>, - info: Option<&'static str>, - metadata: Option<Arc<dyn KgraphMetadata>>, - }, - - AllAggregation { - unsatisfied: Vec<Weak<AnalysisTrace>>, - info: Option<&'static str>, - metadata: Option<Arc<dyn KgraphMetadata>>, - }, - - AnyAggregation { - unsatisfied: Vec<Weak<AnalysisTrace>>, - info: Option<&'static str>, - metadata: Option<Arc<dyn KgraphMetadata>>, - }, - - InAggregation { - expected: Vec<dir::DirValue>, - found: Option<dir::DirValue>, - relation: Relation, - info: Option<&'static str>, - metadata: Option<Arc<dyn KgraphMetadata>>, - }, -} - #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "details", rename_all = "snake_case")] -pub enum AnalysisError { - Graph(GraphError), +pub enum AnalysisError<V: cgraph::ValueNode> { + Graph(cgraph::GraphError<V>), AssertionTrace { - trace: Weak<AnalysisTrace>, + trace: Weak<cgraph::AnalysisTrace<V>>, metadata: Metadata, }, NegationTrace { - trace: Weak<AnalysisTrace>, + trace: Weak<cgraph::AnalysisTrace<V>>, metadata: Vec<Metadata>, }, } -impl AnalysisError { - fn assertion_from_graph_error(metadata: &Metadata, graph_error: GraphError) -> Self { +impl<V: cgraph::ValueNode> AnalysisError<V> { + fn assertion_from_graph_error(metadata: &Metadata, graph_error: cgraph::GraphError<V>) -> Self { match graph_error { - GraphError::AnalysisError(trace) => Self::AssertionTrace { + cgraph::GraphError::AnalysisError(trace) => Self::AssertionTrace { trace, metadata: metadata.clone(), }, @@ -275,9 +56,12 @@ impl AnalysisError { } } - fn negation_from_graph_error(metadata: Vec<&Metadata>, graph_error: GraphError) -> Self { + fn negation_from_graph_error( + metadata: Vec<&Metadata>, + graph_error: cgraph::GraphError<V>, + ) -> Self { match graph_error { - GraphError::AnalysisError(trace) => Self::NegationTrace { + cgraph::GraphError::AnalysisError(trace) => Self::NegationTrace { trace, metadata: metadata.iter().map(|m| (*m).clone()).collect(), }, @@ -287,56 +71,6 @@ impl AnalysisError { } } -#[derive(Debug, Clone, serde::Serialize, thiserror::Error)] -#[serde(tag = "type", content = "info", rename_all = "snake_case")] -pub enum GraphError { - #[error("An edge was not found in the graph")] - EdgeNotFound, - #[error("Attempted to create a conflicting edge between two nodes")] - ConflictingEdgeCreated, - #[error("Cycle detected in graph")] - CycleDetected, - #[error("Domain wasn't found in the Graph")] - DomainNotFound, - #[error("Malformed Graph: {reason}")] - MalformedGraph { reason: String }, - #[error("A node was not found in the graph")] - NodeNotFound, - #[error("A value node was not found: {0:#?}")] - ValueNodeNotFound(dir::DirValue), - #[error("No values provided for an 'in' aggregator node")] - NoInAggregatorValues, - #[error("Error during analysis: {0:#?}")] - AnalysisError(Weak<AnalysisTrace>), -} - -impl GraphError { - fn get_analysis_trace(self) -> Result<Weak<AnalysisTrace>, Self> { - match self { - Self::AnalysisError(trace) => Ok(trace), - _ => Err(self), - } - } -} - -impl PartialEq<dir::DirValue> for NodeValue { - fn eq(&self, other: &dir::DirValue) -> bool { - match self { - Self::Key(dir_key) => *dir_key == other.get_key(), - Self::Value(dir_value) if dir_value.get_key() == other.get_key() => { - if let (Some(left), Some(right)) = - (dir_value.get_num_value(), other.get_num_value()) - { - left.fits(&right) - } else { - dir::DirValue::check_equality(dir_value, other) - } - } - Self::Value(_) => false, - } - } -} - pub struct AnalysisContext { keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>, } @@ -355,33 +89,6 @@ impl AnalysisContext { Self { keywise_values } } - fn check_presence(&self, value: &NodeValue, weak: bool) -> bool { - match value { - NodeValue::Key(k) => self.keywise_values.contains_key(k) || weak, - NodeValue::Value(val) => { - let key = val.get_key(); - let value_set = if let Some(set) = self.keywise_values.get(&key) { - set - } else { - return weak; - }; - - match key.kind.get_type() { - DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => { - value_set.contains(val) - } - DataType::Number => val.get_num_value().map_or(false, |num_val| { - value_set.iter().any(|ctx_val| { - ctx_val - .get_num_value() - .map_or(false, |ctx_num_val| num_val.fits(&ctx_num_val)) - }) - }), - } - } - } - } - pub fn insert(&mut self, value: dir::DirValue) { self.keywise_values .entry(value.get_key()) @@ -400,477 +107,153 @@ impl AnalysisContext { } } -impl<'a> KnowledgeGraphBuilder<'a> { - pub fn new() -> Self { - Self { - domain: utils::DenseMap::new(), - nodes: utils::DenseMap::new(), - edges: utils::DenseMap::new(), - domain_identifier_map: FxHashMap::default(), - value_map: FxHashMap::default(), - edges_map: FxHashMap::default(), - node_info: utils::DenseMap::new(), - node_metadata: utils::DenseMap::new(), - } - } - - pub fn build(self) -> KnowledgeGraph<'a> { - KnowledgeGraph { - domain: self.domain, - nodes: self.nodes, - edges: self.edges, - value_map: self.value_map, - node_info: self.node_info, - node_metadata: self.node_metadata, - } - } - - pub fn make_domain( - &mut self, - domain_identifier: DomainIdentifier<'a>, - domain_description: String, - ) -> Result<DomainId, GraphError> { - Ok(self - .domain_identifier_map - .clone() - .get(&domain_identifier) - .map_or_else( - || { - let domain_id = self.domain.push(DomainInfo { - domain_identifier: domain_identifier.clone(), - domain_description, - }); - self.domain_identifier_map - .insert(domain_identifier.clone(), domain_id); - domain_id - }, - |domain_id| *domain_id, - )) - } - - pub fn make_value_node<M: KgraphMetadata>( - &mut self, - value: NodeValue, - info: Option<&'static str>, - domain_identifiers: Vec<DomainIdentifier<'_>>, - metadata: Option<M>, - ) -> Result<NodeId, GraphError> { - match self.value_map.get(&value).copied() { - Some(node_id) => Ok(node_id), - None => { - let mut domain_ids: Vec<DomainId> = Vec::new(); - domain_identifiers - .iter() - .try_for_each(|ident| { - self.domain_identifier_map - .get(ident) - .map(|id| domain_ids.push(*id)) - }) - .ok_or(GraphError::DomainNotFound)?; - - let node_id = self - .nodes - .push(Node::new(NodeType::Value(value.clone()), domain_ids)); - let _node_info_id = self.node_info.push(info); - - let _node_metadata_id = self - .node_metadata - .push(metadata.map(|meta| -> Arc<dyn KgraphMetadata> { Arc::new(meta) })); - - self.value_map.insert(value, node_id); - Ok(node_id) - } - } - } - - pub fn make_edge( - &mut self, - pred_id: NodeId, - succ_id: NodeId, - strength: Strength, - relation: Relation, - ) -> Result<EdgeId, GraphError> { - self.ensure_node_exists(pred_id)?; - self.ensure_node_exists(succ_id)?; - self.edges_map - .get(&(pred_id, succ_id)) - .copied() - .and_then(|edge_id| self.edges.get(edge_id).cloned().map(|edge| (edge_id, edge))) - .map_or_else( - || { - let edge_id = self.edges.push(Edge { - strength, - relation, - pred: pred_id, - succ: succ_id, - }); - self.edges_map.insert((pred_id, succ_id), edge_id); - - let pred = self - .nodes - .get_mut(pred_id) - .ok_or(GraphError::NodeNotFound)?; - pred.succs.push(edge_id); - - let succ = self - .nodes - .get_mut(succ_id) - .ok_or(GraphError::NodeNotFound)?; - succ.preds.push(edge_id); - - Ok(edge_id) - }, - |(edge_id, edge)| { - if edge.strength == strength && edge.relation == relation { - Ok(edge_id) - } else { - Err(GraphError::ConflictingEdgeCreated) - } - }, - ) - } - - pub fn make_all_aggregator<M: KgraphMetadata>( - &mut self, - nodes: &[(NodeId, Relation, Strength)], - info: Option<&'static str>, - metadata: Option<M>, - domain: Vec<DomainIdentifier<'_>>, - ) -> Result<NodeId, GraphError> { - nodes - .iter() - .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; +impl cgraph::CheckingContext for AnalysisContext { + type Value = dir::DirValue; - let mut domain_ids: Vec<DomainId> = Vec::new(); - domain - .iter() - .try_for_each(|ident| { - self.domain_identifier_map - .get(ident) - .map(|id| domain_ids.push(*id)) - }) - .ok_or(GraphError::DomainNotFound)?; - - let aggregator_id = self - .nodes - .push(Node::new(NodeType::AllAggregator, domain_ids)); - let _aggregator_info_id = self.node_info.push(info); - - let _node_metadata_id = self - .node_metadata - .push(metadata.map(|meta| -> Arc<dyn KgraphMetadata> { Arc::new(meta) })); + fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self + where + L: Into<Self::Value>, + { + let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> = + FxHashMap::default(); - for (node_id, relation, strength) in nodes { - self.make_edge(*node_id, aggregator_id, *strength, *relation)?; + for dir_val in vals.into_iter().map(L::into) { + let key = dir_val.get_key(); + let set = keywise_values.entry(key).or_default(); + set.insert(dir_val); } - Ok(aggregator_id) + Self { keywise_values } } - pub fn make_any_aggregator<M: KgraphMetadata>( - &mut self, - nodes: &[(NodeId, Relation)], - info: Option<&'static str>, - metadata: Option<M>, - domain: Vec<DomainIdentifier<'_>>, - ) -> Result<NodeId, GraphError> { - nodes - .iter() - .try_for_each(|(node_id, _)| self.ensure_node_exists(*node_id))?; - - let mut domain_ids: Vec<DomainId> = Vec::new(); - domain - .iter() - .try_for_each(|ident| { - self.domain_identifier_map - .get(ident) - .map(|id| domain_ids.push(*id)) - }) - .ok_or(GraphError::DomainNotFound)?; - - let aggregator_id = self - .nodes - .push(Node::new(NodeType::AnyAggregator, domain_ids)); - let _aggregator_info_id = self.node_info.push(info); - - let _node_metadata_id = self - .node_metadata - .push(metadata.map(|meta| -> Arc<dyn KgraphMetadata> { Arc::new(meta) })); - - for (node_id, relation) in nodes { - self.make_edge(*node_id, aggregator_id, Strength::Strong, *relation)?; - } + fn check_presence( + &self, + value: &cgraph::NodeValue<dir::DirValue>, + strength: cgraph::Strength, + ) -> bool { + match value { + cgraph::NodeValue::Key(k) => { + self.keywise_values.contains_key(k) || matches!(strength, cgraph::Strength::Weak) + } - Ok(aggregator_id) - } + cgraph::NodeValue::Value(val) => { + let key = val.get_key(); + let value_set = if let Some(set) = self.keywise_values.get(&key) { + set + } else { + return matches!(strength, cgraph::Strength::Weak); + }; - pub fn make_in_aggregator<M: KgraphMetadata>( - &mut self, - values: Vec<dir::DirValue>, - info: Option<&'static str>, - metadata: Option<M>, - domain: Vec<DomainIdentifier<'_>>, - ) -> Result<NodeId, GraphError> { - let key = values - .first() - .ok_or(GraphError::NoInAggregatorValues)? - .get_key(); - - for val in &values { - if val.get_key() != key { - Err(GraphError::MalformedGraph { - reason: "Values for 'In' aggregator not of same key".to_string(), - })?; + match key.kind.get_type() { + DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => { + value_set.contains(val) + } + DataType::Number => val.get_num_value().map_or(false, |num_val| { + value_set.iter().any(|ctx_val| { + ctx_val + .get_num_value() + .map_or(false, |ctx_num_val| num_val.fits(&ctx_num_val)) + }) + }), + } } } - - let mut domain_ids: Vec<DomainId> = Vec::new(); - domain - .iter() - .try_for_each(|ident| { - self.domain_identifier_map - .get(ident) - .map(|id| domain_ids.push(*id)) - }) - .ok_or(GraphError::DomainNotFound)?; - - let node_id = self.nodes.push(Node::new( - NodeType::InAggregator(FxHashSet::from_iter(values)), - domain_ids, - )); - let _aggregator_info_id = self.node_info.push(info); - - let _node_metadata_id = self - .node_metadata - .push(metadata.map(|meta| -> Arc<dyn KgraphMetadata> { Arc::new(meta) })); - - Ok(node_id) } - fn ensure_node_exists(&self, id: NodeId) -> Result<(), GraphError> { - if self.nodes.contains_key(id) { - Ok(()) - } else { - Err(GraphError::NodeNotFound) - } + fn get_values_by_key( + &self, + key: &<Self::Value as cgraph::ValueNode>::Key, + ) -> Option<Vec<Self::Value>> { + self.keywise_values + .get(key) + .map(|set| set.iter().cloned().collect()) } } -impl<'a> KnowledgeGraph<'a> { - fn check_node( +pub trait CgraphExt { + fn key_analysis( &self, + key: dir::DirKey, ctx: &AnalysisContext, - node_id: NodeId, - relation: Relation, - strength: Strength, - memo: &mut Memoization, - ) -> Result<(), GraphError> { - let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; - if let Some(already_memo) = memo.get(&(node_id, relation, strength)) { - already_memo - .clone() - .map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err))) - } else { - match &node.node_type { - NodeType::AllAggregator => { - let mut unsatisfied = Vec::<Weak<AnalysisTrace>>::new(); - - for edge_id in node.preds.iter().copied() { - let edge = self.edges.get(edge_id).ok_or(GraphError::EdgeNotFound)?; - - if let Err(e) = - self.check_node(ctx, edge.pred, edge.relation, edge.strength, memo) - { - unsatisfied.push(e.get_analysis_trace()?); - } - } - - if !unsatisfied.is_empty() { - let err = Arc::new(AnalysisTrace::AllAggregation { - unsatisfied, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err))) - } else { - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } - } - - NodeType::AnyAggregator => { - let mut unsatisfied = Vec::<Weak<AnalysisTrace>>::new(); - let mut matched_one = false; - - for edge_id in node.preds.iter().copied() { - let edge = self.edges.get(edge_id).ok_or(GraphError::EdgeNotFound)?; - - if let Err(e) = - self.check_node(ctx, edge.pred, edge.relation, edge.strength, memo) - { - unsatisfied.push(e.get_analysis_trace()?); - } else { - matched_one = true; - } - } - - if matched_one || node.preds.is_empty() { - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } else { - let err = Arc::new(AnalysisTrace::AnyAggregation { - unsatisfied: unsatisfied.clone(), - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err))) - } - } + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>>; - NodeType::InAggregator(expected) => { - let the_key = expected - .iter() - .next() - .ok_or_else(|| GraphError::MalformedGraph { - reason: - "An OnlyIn aggregator node must have at least one expected value" - .to_string(), - })? - .get_key(); - - let ctx_vals = if let Some(vals) = ctx.keywise_values.get(&the_key) { - vals - } else { - return if let Strength::Weak = strength { - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } else { - let err = Arc::new(AnalysisTrace::InAggregation { - expected: expected.iter().cloned().collect(), - found: None, - relation, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err))) - }; - }; - - let relation_bool: bool = relation.into(); - for ctx_value in ctx_vals { - if expected.contains(ctx_value) != relation_bool { - let err = Arc::new(AnalysisTrace::InAggregation { - expected: expected.iter().cloned().collect(), - found: Some(ctx_value.clone()), - relation, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; - } - } + fn value_analysis( + &self, + val: dir::DirValue, + ctx: &AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>>; - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } + fn check_value_validity( + &self, + val: dir::DirValue, + analysis_ctx: &AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<bool, cgraph::GraphError<dir::DirValue>>; - NodeType::Value(val) => { - let in_context = ctx.check_presence(val, matches!(strength, Strength::Weak)); - let relation_bool: bool = relation.into(); - - if in_context != relation_bool { - let err = Arc::new(AnalysisTrace::Value { - value: val.clone(), - relation, - predecessors: None, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; - } + fn key_value_analysis( + &self, + val: dir::DirValue, + ctx: &AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>>; - if !relation_bool { - memo.insert((node_id, relation, strength), Ok(())); - return Ok(()); - } + fn assertion_analysis( + &self, + positive_ctx: &[(&dir::DirValue, &Metadata)], + analysis_ctx: &AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>>; - let mut errors = Vec::<Weak<AnalysisTrace>>::new(); - let mut matched_one = false; - - for edge_id in node.preds.iter().copied() { - let edge = self.edges.get(edge_id).ok_or(GraphError::EdgeNotFound)?; - let result = - self.check_node(ctx, edge.pred, edge.relation, edge.strength, memo); - - match (edge.strength, result) { - (Strength::Strong, Err(trace)) => { - let err = Arc::new(AnalysisTrace::Value { - value: val.clone(), - relation, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - predecessors: Some(ValueTracePredecessor::Mandatory(Box::new( - trace.get_analysis_trace()?, - ))), - }); - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; - } - - (Strength::Strong, Ok(_)) => { - matched_one = true; - } - - (Strength::Normal | Strength::Weak, Err(trace)) => { - errors.push(trace.get_analysis_trace()?); - } - - (Strength::Normal | Strength::Weak, Ok(_)) => { - matched_one = true; - } - } - } + fn negation_analysis( + &self, + negative_ctx: &[(&[dir::DirValue], &Metadata)], + analysis_ctx: &mut AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>>; - if matched_one || node.preds.is_empty() { - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } else { - let err = Arc::new(AnalysisTrace::Value { - value: val.clone(), - relation, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - predecessors: Some(ValueTracePredecessor::OneOf(errors.clone())), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err))) - } - } - } - } - } + fn perform_context_analysis( + &self, + ctx: &types::ConjunctiveContext<'_>, + memo: &mut cgraph::Memoization<dir::DirValue>, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>>; +} +impl CgraphExt for cgraph::ConstraintGraph<'_, dir::DirValue> { fn key_analysis( &self, key: dir::DirKey, ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), GraphError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.value_map - .get(&NodeValue::Key(key)) + .get(&cgraph::NodeValue::Key(key)) .map_or(Ok(()), |node_id| { - self.check_node(ctx, *node_id, Relation::Positive, Strength::Strong, memo) + self.check_node( + ctx, + *node_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + memo, + cycle_map, + domains, + ) }) } @@ -878,22 +261,34 @@ impl<'a> KnowledgeGraph<'a> { &self, val: dir::DirValue, ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), GraphError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.value_map - .get(&NodeValue::Value(val)) + .get(&cgraph::NodeValue::Value(val)) .map_or(Ok(()), |node_id| { - self.check_node(ctx, *node_id, Relation::Positive, Strength::Strong, memo) + self.check_node( + ctx, + *node_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + memo, + cycle_map, + domains, + ) }) } - pub fn check_value_validity( + fn check_value_validity( &self, val: dir::DirValue, analysis_ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<bool, GraphError> { - let maybe_node_id = self.value_map.get(&NodeValue::Value(val)); + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<bool, cgraph::GraphError<dir::DirValue>> { + let maybe_node_id = self.value_map.get(&cgraph::NodeValue::Value(val)); let node_id = if let Some(nid) = maybe_node_id { nid @@ -904,9 +299,11 @@ impl<'a> KnowledgeGraph<'a> { let result = self.check_node( analysis_ctx, *node_id, - Relation::Positive, - Strength::Weak, + cgraph::Relation::Positive, + cgraph::Strength::Weak, memo, + cycle_map, + domains, ); match result { @@ -918,24 +315,28 @@ impl<'a> KnowledgeGraph<'a> { } } - pub fn key_value_analysis( + fn key_value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), GraphError> { - self.key_analysis(val.get_key(), ctx, memo) - .and_then(|_| self.value_analysis(val, ctx, memo)) + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>> { + self.key_analysis(val.get_key(), ctx, memo, cycle_map, domains) + .and_then(|_| self.value_analysis(val, ctx, memo, cycle_map, domains)) } fn assertion_analysis( &self, positive_ctx: &[(&dir::DirValue, &Metadata)], analysis_ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), AnalysisError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>> { positive_ctx.iter().try_for_each(|(value, metadata)| { - self.key_value_analysis((*value).clone(), analysis_ctx, memo) + self.key_value_analysis((*value).clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(metadata, e)) }) } @@ -944,8 +345,10 @@ impl<'a> KnowledgeGraph<'a> { &self, negative_ctx: &[(&[dir::DirValue], &Metadata)], analysis_ctx: &mut AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), AnalysisError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>> { let mut keywise_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default(); let mut keywise_negation: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> = FxHashMap::default(); @@ -974,7 +377,7 @@ impl<'a> KnowledgeGraph<'a> { let all_metadata = keywise_metadata.remove(&key).unwrap_or_default(); let first_metadata = all_metadata.first().cloned().cloned().unwrap_or_default(); - self.key_analysis(key.clone(), analysis_ctx, memo) + self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?; let mut value_set = if let Some(set) = key.kind.get_value_set() { @@ -987,7 +390,7 @@ impl<'a> KnowledgeGraph<'a> { for value in value_set { analysis_ctx.insert(value.clone()); - self.value_analysis(value.clone(), analysis_ctx, memo) + self.value_analysis(value.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| { AnalysisError::negation_from_graph_error(all_metadata.clone(), e) })?; @@ -998,11 +401,12 @@ impl<'a> KnowledgeGraph<'a> { Ok(()) } - pub fn perform_context_analysis( + fn perform_context_analysis( &self, ctx: &types::ConjunctiveContext<'_>, - memo: &mut Memoization, - ) -> Result<(), AnalysisError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>> { let mut analysis_ctx = AnalysisContext::from_dir_values( ctx.iter() .filter_map(|ctx_val| ctx_val.value.get_assertion().cloned()), @@ -1017,7 +421,13 @@ impl<'a> KnowledgeGraph<'a> { .map(|val| (val, ctx_val.metadata)) }) .collect::<Vec<_>>(); - self.assertion_analysis(&positive_ctx, &analysis_ctx, memo)?; + self.assertion_analysis( + &positive_ctx, + &analysis_ctx, + memo, + &mut cgraph::CycleCheck::new(), + domains, + )?; let negative_ctx = ctx .iter() @@ -1028,127 +438,38 @@ impl<'a> KnowledgeGraph<'a> { .map(|vals| (vals, ctx_val.metadata)) }) .collect::<Vec<_>>(); - self.negation_analysis(&negative_ctx, &mut analysis_ctx, memo)?; + self.negation_analysis( + &negative_ctx, + &mut analysis_ctx, + memo, + &mut cgraph::CycleCheck::new(), + domains, + )?; Ok(()) } - - pub fn combine<'b>(g1: &'b Self, g2: &'b Self) -> Result<Self, GraphError> { - let mut node_builder = KnowledgeGraphBuilder::new(); - let mut g1_old2new_id = utils::DenseMap::<NodeId, NodeId>::new(); - let mut g2_old2new_id = utils::DenseMap::<NodeId, NodeId>::new(); - let mut g1_old2new_domain_id = utils::DenseMap::<DomainId, DomainId>::new(); - let mut g2_old2new_domain_id = utils::DenseMap::<DomainId, DomainId>::new(); - - let add_domain = |node_builder: &mut KnowledgeGraphBuilder<'a>, - domain: DomainInfo<'a>| - -> Result<DomainId, GraphError> { - node_builder.make_domain(domain.domain_identifier, domain.domain_description) - }; - - let add_node = |node_builder: &mut KnowledgeGraphBuilder<'a>, - node: &Node, - domains: Vec<DomainIdentifier<'_>>| - -> Result<NodeId, GraphError> { - match &node.node_type { - NodeType::Value(node_value) => { - node_builder.make_value_node(node_value.clone(), None, domains, None::<()>) - } - - NodeType::AllAggregator => { - Ok(node_builder.make_all_aggregator(&[], None, None::<()>, domains)?) - } - - NodeType::AnyAggregator => { - Ok(node_builder.make_any_aggregator(&[], None, None::<()>, Vec::new())?) - } - - NodeType::InAggregator(expected) => Ok(node_builder.make_in_aggregator( - expected.iter().cloned().collect(), - None, - None::<()>, - Vec::new(), - )?), - } - }; - - for (_old_domain_id, domain) in g1.domain.iter() { - let new_domain_id = add_domain(&mut node_builder, domain.clone())?; - g1_old2new_domain_id.push(new_domain_id); - } - - for (_old_domain_id, domain) in g2.domain.iter() { - let new_domain_id = add_domain(&mut node_builder, domain.clone())?; - g2_old2new_domain_id.push(new_domain_id); - } - - for (_old_node_id, node) in g1.nodes.iter() { - let mut domain_identifiers: Vec<DomainIdentifier<'_>> = Vec::new(); - for domain_id in &node.domain_ids { - match g1.domain.get(*domain_id) { - Some(domain) => domain_identifiers.push(domain.domain_identifier.clone()), - None => return Err(GraphError::DomainNotFound), - } - } - let new_node_id = add_node(&mut node_builder, node, domain_identifiers.clone())?; - g1_old2new_id.push(new_node_id); - } - - for (_old_node_id, node) in g2.nodes.iter() { - let mut domain_identifiers: Vec<DomainIdentifier<'_>> = Vec::new(); - for domain_id in &node.domain_ids { - match g2.domain.get(*domain_id) { - Some(domain) => domain_identifiers.push(domain.domain_identifier.clone()), - None => return Err(GraphError::DomainNotFound), - } - } - let new_node_id = add_node(&mut node_builder, node, domain_identifiers.clone())?; - g2_old2new_id.push(new_node_id); - } - - for edge in g1.edges.values() { - let new_pred_id = g1_old2new_id - .get(edge.pred) - .ok_or(GraphError::NodeNotFound)?; - let new_succ_id = g1_old2new_id - .get(edge.succ) - .ok_or(GraphError::NodeNotFound)?; - - node_builder.make_edge(*new_pred_id, *new_succ_id, edge.strength, edge.relation)?; - } - - for edge in g2.edges.values() { - let new_pred_id = g2_old2new_id - .get(edge.pred) - .ok_or(GraphError::NodeNotFound)?; - let new_succ_id = g2_old2new_id - .get(edge.succ) - .ok_or(GraphError::NodeNotFound)?; - - node_builder.make_edge(*new_pred_id, *new_succ_id, edge.strength, edge.relation)?; - } - - Ok(node_builder.build()) - } } #[cfg(test)] mod test { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use std::ops::Deref; + use euclid_macros::knowledge; + use hyperswitch_constraint_graph::CycleCheck; use super::*; use crate::{dirval, frontend::dir::enums}; #[test] fn test_strong_positive_relation_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) ->> CaptureMethod(Automatic); PaymentMethod(not Wallet) & PaymentMethod(not PayLater) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1156,6 +477,8 @@ mod test { dirval!(PaymentMethod = Card), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1163,15 +486,17 @@ mod test { #[test] fn test_strong_positive_relation_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) ->> CaptureMethod(Automatic); PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([dirval!(CaptureMethod = Automatic)]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1179,11 +504,11 @@ mod test { #[test] fn test_strong_negative_relation_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1191,6 +516,8 @@ mod test { dirval!(PaymentMethod = Card), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1198,11 +525,11 @@ mod test { #[test] fn test_strong_negative_relation_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1210,6 +537,8 @@ mod test { dirval!(PaymentMethod = Wallet), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1217,11 +546,11 @@ mod test { #[test] fn test_normal_one_of_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(Wallet) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1229,12 +558,14 @@ mod test { dirval!(PaymentMethod = PayLater), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(matches!( *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected Arc"), - AnalysisTrace::Value { - predecessors: Some(ValueTracePredecessor::OneOf(_)), + cgraph::AnalysisTrace::Value { + predecessors: Some(cgraph::error::ValueTracePredecessor::OneOf(_)), .. } )); @@ -1242,10 +573,10 @@ mod test { #[test] fn test_all_aggregator_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1253,6 +584,8 @@ mod test { dirval!(CaptureMethod = Automatic), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1260,10 +593,10 @@ mod test { #[test] fn test_all_aggregator_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1271,6 +604,8 @@ mod test { dirval!(PaymentMethod = PayLater), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1278,10 +613,10 @@ mod test { #[test] fn test_all_aggregator_mandatory_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; - let mut memo = Memoization::new(); + let mut memo = cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1289,13 +624,15 @@ mod test { dirval!(PaymentMethod = PayLater), ]), &mut memo, + &mut CycleCheck::new(), + None, ); assert!(matches!( *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected Arc"), - AnalysisTrace::Value { - predecessors: Some(ValueTracePredecessor::Mandatory(_)), + cgraph::AnalysisTrace::Value { + predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(_)), .. } )); @@ -1303,10 +640,10 @@ mod test { #[test] fn test_in_aggregator_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1315,6 +652,8 @@ mod test { dirval!(PaymentMethod = Wallet), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1322,10 +661,10 @@ mod test { #[test] fn test_in_aggregator_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1335,6 +674,8 @@ mod test { dirval!(PaymentMethod = PayLater), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1342,10 +683,10 @@ mod test { #[test] fn test_not_in_aggregator_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1354,6 +695,8 @@ mod test { dirval!(PaymentMethod = BankRedirect), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1361,10 +704,10 @@ mod test { #[test] fn test_not_in_aggregator_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1374,6 +717,8 @@ mod test { dirval!(PaymentMethod = Card), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1381,10 +726,10 @@ mod test { #[test] fn test_in_aggregator_failure_trace() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(in [Card, Wallet]) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1394,10 +739,12 @@ mod test { dirval!(PaymentMethod = PayLater), ]), memo, + &mut CycleCheck::new(), + None, ); - if let AnalysisTrace::Value { - predecessors: Some(ValueTracePredecessor::Mandatory(agg_error)), + if let cgraph::AnalysisTrace::Value { + predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(agg_error)), .. } = Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected arc") @@ -1405,7 +752,7 @@ mod test { { assert!(matches!( *Weak::upgrade(agg_error.deref()).expect("Expected Arc"), - AnalysisTrace::InAggregation { + cgraph::AnalysisTrace::InAggregation { found: Some(dir::DirValue::PaymentMethod(enums::PaymentMethod::PayLater)), .. } @@ -1416,43 +763,43 @@ mod test { } #[test] - fn _test_memoization_in_kgraph() { - let mut builder = KnowledgeGraphBuilder::new(); + fn test_memoization_in_kgraph() { + let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_1 = builder.make_value_node( - NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, - Vec::new(), None::<()>, ); let _node_2 = builder.make_value_node( - NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)), + cgraph::NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)), None, - Vec::new(), None::<()>, ); let _node_3 = builder.make_value_node( - NodeValue::Value(dir::DirValue::BusinessCountry( + cgraph::NodeValue::Value(dir::DirValue::BusinessCountry( enums::BusinessCountry::UnitedStatesOfAmerica, )), None, - Vec::new(), None::<()>, ); - let mut memo = Memoization::new(); + let mut memo = cgraph::Memoization::new(); + let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( - _node_1.expect("node1 constructtion failed"), - _node_2.clone().expect("node2 construction failed"), - Strength::Strong, - Relation::Positive, + _node_1, + _node_2, + cgraph::Strength::Strong, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( - _node_2.expect("node2 construction failed"), - _node_3.clone().expect("node3 construction failed"), - Strength::Strong, - Relation::Positive, + _node_2, + _node_3, + cgraph::Strength::Strong, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, ) .expect("Failed to an edge"); let graph = builder.build(); @@ -1464,15 +811,263 @@ mod test { dirval!(BusinessCountry = UnitedStatesOfAmerica), ]), &mut memo, + &mut cycle_map, + None, ); let _answer = memo - .0 .get(&( - _node_3.expect("node3 construction failed"), - Relation::Positive, - Strength::Strong, + _node_3, + cgraph::Relation::Positive, + cgraph::Strength::Strong, )) .expect("Memoization not workng"); matches!(_answer, Ok(())); } + + #[test] + fn test_cycle_resolution_in_graph() { + let mut builder = cgraph::ConstraintGraphBuilder::new(); + let _node_1 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), + None, + None::<()>, + ); + let _node_2 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), + None, + None::<()>, + ); + let mut memo = cgraph::Memoization::new(); + let mut cycle_map = cgraph::CycleCheck::new(); + let _edge_1 = builder + .make_edge( + _node_1, + _node_2, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_2 = builder + .make_edge( + _node_2, + _node_1, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to an edge"); + let graph = builder.build(); + let _result = graph.key_value_analysis( + dirval!(PaymentMethod = Wallet), + &AnalysisContext::from_dir_values([ + dirval!(PaymentMethod = Wallet), + dirval!(PaymentMethod = Card), + ]), + &mut memo, + &mut cycle_map, + None, + ); + + assert!(_result.is_ok()); + } + + #[test] + fn test_cycle_resolution_in_graph1() { + let mut builder = cgraph::ConstraintGraphBuilder::new(); + let _node_1 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( + enums::CaptureMethod::Automatic, + )), + None, + None::<()>, + ); + + let _node_2 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), + None, + None::<()>, + ); + let _node_3 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), + None, + None::<()>, + ); + let mut memo = cgraph::Memoization::new(); + let mut cycle_map = cgraph::CycleCheck::new(); + + let _edge_1 = builder + .make_edge( + _node_1, + _node_2, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_2 = builder + .make_edge( + _node_1, + _node_3, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_3 = builder + .make_edge( + _node_2, + _node_1, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_4 = builder + .make_edge( + _node_3, + _node_1, + cgraph::Strength::Strong, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + + let graph = builder.build(); + let _result = graph.key_value_analysis( + dirval!(CaptureMethod = Automatic), + &AnalysisContext::from_dir_values([ + dirval!(PaymentMethod = Card), + dirval!(PaymentMethod = Wallet), + dirval!(CaptureMethod = Automatic), + ]), + &mut memo, + &mut cycle_map, + None, + ); + + assert!(_result.is_ok()); + } + + #[test] + fn test_cycle_resolution_in_graph2() { + let mut builder = cgraph::ConstraintGraphBuilder::new(); + let _node_0 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::BillingCountry( + enums::BillingCountry::Afghanistan, + )), + None, + None::<()>, + ); + + let _node_1 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( + enums::CaptureMethod::Automatic, + )), + None, + None::<()>, + ); + + let _node_2 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), + None, + None::<()>, + ); + let _node_3 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), + None, + None::<()>, + ); + + let _node_4 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentCurrency(enums::PaymentCurrency::USD)), + None, + None::<()>, + ); + + let mut memo = cgraph::Memoization::new(); + let mut cycle_map = cgraph::CycleCheck::new(); + + let _edge_1 = builder + .make_edge( + _node_0, + _node_1, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_2 = builder + .make_edge( + _node_1, + _node_2, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_3 = builder + .make_edge( + _node_1, + _node_3, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_4 = builder + .make_edge( + _node_3, + _node_4, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_5 = builder + .make_edge( + _node_2, + _node_4, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + + let _edge_6 = builder + .make_edge( + _node_4, + _node_1, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_7 = builder + .make_edge( + _node_4, + _node_0, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + + let graph = builder.build(); + let _result = graph.key_value_analysis( + dirval!(BillingCountry = Afghanistan), + &AnalysisContext::from_dir_values([ + dirval!(PaymentCurrency = USD), + dirval!(PaymentMethod = Card), + dirval!(PaymentMethod = Wallet), + dirval!(CaptureMethod = Automatic), + dirval!(BillingCountry = Afghanistan), + ]), + &mut memo, + &mut cycle_map, + None, + ); + + assert!(_result.is_ok()); + } } diff --git a/crates/euclid/src/dssa/truth.rs b/crates/euclid/src/dssa/truth.rs index 17e6e728e68..388180eed5b 100644 --- a/crates/euclid/src/dssa/truth.rs +++ b/crates/euclid/src/dssa/truth.rs @@ -1,29 +1,30 @@ use euclid_macros::knowledge; use once_cell::sync::Lazy; -use crate::dssa::graph; +use crate::{dssa::graph::euclid_graph_prelude, frontend::dir}; -pub static ANALYSIS_GRAPH: Lazy<graph::KnowledgeGraph<'_>> = Lazy::new(|| { - knowledge! {crate - // Payment Method should be `Card` for a CardType to be present - PaymentMethod(Card) ->> CardType(any); +pub static ANALYSIS_GRAPH: Lazy<hyperswitch_constraint_graph::ConstraintGraph<'_, dir::DirValue>> = + Lazy::new(|| { + knowledge! { + // Payment Method should be `Card` for a CardType to be present + PaymentMethod(Card) ->> CardType(any); - // Payment Method should be `PayLater` for a PayLaterType to be present - PaymentMethod(PayLater) ->> PayLaterType(any); + // Payment Method should be `PayLater` for a PayLaterType to be present + PaymentMethod(PayLater) ->> PayLaterType(any); - // Payment Method should be `Wallet` for a WalletType to be present - PaymentMethod(Wallet) ->> WalletType(any); + // Payment Method should be `Wallet` for a WalletType to be present + PaymentMethod(Wallet) ->> WalletType(any); - // Payment Method should be `BankRedirect` for a BankRedirectType to - // be present - PaymentMethod(BankRedirect) ->> BankRedirectType(any); + // Payment Method should be `BankRedirect` for a BankRedirectType to + // be present + PaymentMethod(BankRedirect) ->> BankRedirectType(any); - // Payment Method should be `BankTransfer` for a BankTransferType to - // be present - PaymentMethod(BankTransfer) ->> BankTransferType(any); + // Payment Method should be `BankTransfer` for a BankTransferType to + // be present + PaymentMethod(BankTransfer) ->> BankTransferType(any); - // Payment Method should be `GiftCard` for a GiftCardType to - // be present - PaymentMethod(GiftCard) ->> GiftCardType(any); - } -}); + // Payment Method should be `GiftCard` for a GiftCardType to + // be present + PaymentMethod(GiftCard) ->> GiftCardType(any); + } + }); diff --git a/crates/euclid/src/dssa/types.rs b/crates/euclid/src/dssa/types.rs index 4070e0825ef..df54de2dd99 100644 --- a/crates/euclid/src/dssa/types.rs +++ b/crates/euclid/src/dssa/types.rs @@ -140,7 +140,10 @@ pub enum AnalysisErrorType { negation_metadata: Metadata, }, #[error("Graph analysis error: {0:#?}")] - GraphAnalysis(graph::AnalysisError, graph::Memoization), + GraphAnalysis( + graph::AnalysisError<dir::DirValue>, + hyperswitch_constraint_graph::Memoization<dir::DirValue>, + ), #[error("State machine error")] StateMachine(dssa::state_machine::StateMachineError), #[error("Unsupported program key '{0}'")] diff --git a/crates/euclid/src/lib.rs b/crates/euclid/src/lib.rs index d64297437ae..261b3dc02d6 100644 --- a/crates/euclid/src/lib.rs +++ b/crates/euclid/src/lib.rs @@ -4,4 +4,3 @@ pub mod dssa; pub mod enums; pub mod frontend; pub mod types; -pub mod utils; diff --git a/crates/euclid/src/utils.rs b/crates/euclid/src/utils.rs deleted file mode 100644 index e8cb7901f0d..00000000000 --- a/crates/euclid/src/utils.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod dense_map; - -pub use dense_map::{DenseMap, EntityId}; diff --git a/crates/euclid_macros/src/inner/knowledge.rs b/crates/euclid_macros/src/inner/knowledge.rs index 9f33a6871c5..a9c453b42c6 100644 --- a/crates/euclid_macros/src/inner/knowledge.rs +++ b/crates/euclid_macros/src/inner/knowledge.rs @@ -329,19 +329,17 @@ impl ToString for Scope { #[derive(Clone)] struct Program { rules: Vec<Rc<Rule>>, - scope: Scope, } impl Parse for Program { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { - let scope: Scope = input.parse()?; let mut rules: Vec<Rc<Rule>> = Vec::new(); while !input.is_empty() { rules.push(Rc::new(input.parse::<Rule>()?)); } - Ok(Self { rules, scope }) + Ok(Self { rules }) } } @@ -502,12 +500,12 @@ impl GenContext { let key = format_ident!("{}", &atom.key); let the_value = match &atom.value { ValueType::Any => quote! { - NodeValue::Key(DirKey::new(DirKeyKind::#key,None)) + cgraph::NodeValue::Key(DirKey::new(DirKeyKind::#key,None)) }, ValueType::EnumVariant(variant) => { let variant = format_ident!("{}", variant); quote! { - NodeValue::Value(DirValue::#key(#key::#variant)) + cgraph::NodeValue::Value(DirValue::#key(#key::#variant)) } } ValueType::Number { number, comparison } => { @@ -530,7 +528,7 @@ impl GenContext { }; quote! { - NodeValue::Value(DirValue::#key(NumValue { + cgraph::NodeValue::Value(DirValue::#key(NumValue { number: #number, refinement: #comp_type, })) @@ -539,7 +537,7 @@ impl GenContext { }; let compiled = quote! { - let #identifier = graph.make_value_node(#the_value, None, Vec::new(), None::<()>).expect("NodeId derivation failed"); + let #identifier = graph.make_value_node(#the_value, None, None::<()>); }; tokens.extend(compiled); @@ -581,7 +579,6 @@ impl GenContext { Vec::from_iter([#(#values_tokens),*]), None, None::<()>, - Vec::new(), ).expect("Failed to make In aggregator"); }; @@ -606,7 +603,7 @@ impl GenContext { for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); tokens.extend(quote! { - graph.make_edge(#from_node, #rhs_ident, Strength::#strength, Relation::#relation) + graph.make_edge(#from_node, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::#relation, None::<cgraph::DomainId>) .expect("Failed to make edge"); }); } @@ -614,16 +611,18 @@ impl GenContext { let mut all_agg_nodes: Vec<TokenStream> = Vec::with_capacity(node_details.len()); for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); - all_agg_nodes.push(quote! { (#from_node, Relation::#relation, Strength::Strong) }); + all_agg_nodes.push( + quote! { (#from_node, cgraph::Relation::#relation, cgraph::Strength::Strong) }, + ); } let strength = format_ident!("{}", rule.strength.to_string()); let (agg_node_ident, _) = self.next_node_ident(); tokens.extend(quote! { - let #agg_node_ident = graph.make_all_aggregator(&[#(#all_agg_nodes),*], None, None::<()>, Vec::new()) + let #agg_node_ident = graph.make_all_aggregator(&[#(#all_agg_nodes),*], None, None::<()>, None) .expect("Failed to make all aggregator node"); - graph.make_edge(#agg_node_ident, #rhs_ident, Strength::#strength, Relation::Positive) + graph.make_edge(#agg_node_ident, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::Positive, None::<cgraph::DomainId>) .expect("Failed to create all aggregator edge"); }); @@ -638,21 +637,10 @@ impl GenContext { self.compile_rule(rule, &mut tokens)?; } - let scope = match &program.scope { - Scope::Crate => quote! { crate }, - Scope::Extern => quote! { euclid }, - }; - let compiled = quote! {{ - use #scope::{ - dssa::graph::*, - types::*, - frontend::dir::{*, enums::*}, - }; - - use rustc_hash::{FxHashMap, FxHashSet}; + use euclid_graph_prelude::*; - let mut graph = KnowledgeGraphBuilder::new(); + let mut graph = cgraph::ConstraintGraphBuilder::new(); #tokens diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index 6f5d3ec9cc3..293940f27c4 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -23,6 +23,7 @@ payouts = ["api_models/payouts", "euclid/payouts"] [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } connector_configs = { version = "0.1.0", path = "../connector_configs" } euclid = { version = "0.1.0", path = "../euclid", features = [] } diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index 36af0dc2d23..4920243bcc0 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -20,11 +20,7 @@ use currency_conversion::{ }; use euclid::{ backend::{inputs, interpreter::InterpreterBackend, EuclidBackend}, - dssa::{ - self, analyzer, - graph::{self, Memoization}, - state_machine, truth, - }, + dssa::{self, analyzer, graph::CgraphExt, state_machine, truth}, frontend::{ ast, dir::{self, enums as dir_enums, EuclidDirFilter}, @@ -38,7 +34,7 @@ use crate::utils::JsResultExt; type JsResult = Result<JsValue, JsValue>; struct SeedData<'a> { - kgraph: graph::KnowledgeGraph<'a>, + cgraph: hyperswitch_constraint_graph::ConstraintGraph<'a, dir::DirValue>, connectors: Vec<ast::ConnectorChoice>, } @@ -98,11 +94,12 @@ pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult { let mca_graph = kgraph_utils::mca::make_mca_graph(mcas).err_to_js()?; let analysis_graph = - graph::KnowledgeGraph::combine(&mca_graph, &truth::ANALYSIS_GRAPH).err_to_js()?; + hyperswitch_constraint_graph::ConstraintGraph::combine(&mca_graph, &truth::ANALYSIS_GRAPH) + .err_to_js()?; SEED_DATA .set(SeedData { - kgraph: analysis_graph, + cgraph: analysis_graph, connectors, }) .map_err(|_| "Knowledge Graph has been already seeded".to_string()) @@ -138,8 +135,12 @@ pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { // Standalone conjunctive context analysis to ensure the context itself is valid before // checking it against merchant's connectors seed_data - .kgraph - .perform_context_analysis(ctx, &mut Memoization::new()) + .cgraph + .perform_context_analysis( + ctx, + &mut hyperswitch_constraint_graph::Memoization::new(), + None, + ) .err_to_js()?; // Update conjunctive context and run analysis on all of merchant's connectors. @@ -150,9 +151,11 @@ pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { let ctx_val = dssa::types::ContextValue::assertion(choice, &dummy_meta); ctx.push(ctx_val); - let analysis_result = seed_data - .kgraph - .perform_context_analysis(ctx, &mut Memoization::new()); + let analysis_result = seed_data.cgraph.perform_context_analysis( + ctx, + &mut hyperswitch_constraint_graph::Memoization::new(), + None, + ); if analysis_result.is_err() { invalid_connectors.insert(conn.clone()); } @@ -171,7 +174,7 @@ pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { #[wasm_bindgen(js_name = analyzeProgram)] pub fn analyze_program(js_program: JsValue) -> JsResult { let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(js_program)?; - analyzer::analyze(program, SEED_DATA.get().map(|sd| &sd.kgraph)).err_to_js()?; + analyzer::analyze(program, SEED_DATA.get().map(|sd| &sd.cgraph)).err_to_js()?; Ok(JsValue::NULL) } diff --git a/crates/hyperswitch_constraint_graph/Cargo.toml b/crates/hyperswitch_constraint_graph/Cargo.toml new file mode 100644 index 00000000000..425855a05b0 --- /dev/null +++ b/crates/hyperswitch_constraint_graph/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "hyperswitch_constraint_graph" +description = "Constraint Graph Framework for modeling Domain-Specific Constraints" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +erased-serde = "0.3.28" +rustc-hash = "1.1.0" +serde = { version = "1.0.163", features = ["derive", "rc"] } +serde_json = "1.0.96" +strum = { version = "0.25", features = ["derive"] } +thiserror = "1.0.43" diff --git a/crates/hyperswitch_constraint_graph/src/builder.rs b/crates/hyperswitch_constraint_graph/src/builder.rs new file mode 100644 index 00000000000..c1343eff885 --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/builder.rs @@ -0,0 +1,283 @@ +use std::sync::Arc; + +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{ + dense_map::DenseMap, + error::GraphError, + graph::ConstraintGraph, + types::{ + DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, Metadata, Node, NodeId, NodeType, + NodeValue, Relation, Strength, ValueNode, + }, +}; + +pub enum DomainIdOrIdentifier<'a> { + DomainId(DomainId), + DomainIdentifier(DomainIdentifier<'a>), +} + +impl<'a> From<&'a str> for DomainIdOrIdentifier<'a> { + fn from(value: &'a str) -> Self { + Self::DomainIdentifier(DomainIdentifier::new(value)) + } +} + +impl From<DomainId> for DomainIdOrIdentifier<'_> { + fn from(value: DomainId) -> Self { + Self::DomainId(value) + } +} + +pub struct ConstraintGraphBuilder<'a, V: ValueNode> { + domain: DenseMap<DomainId, DomainInfo<'a>>, + nodes: DenseMap<NodeId, Node<V>>, + edges: DenseMap<EdgeId, Edge>, + domain_identifier_map: FxHashMap<DomainIdentifier<'a>, DomainId>, + value_map: FxHashMap<NodeValue<V>, NodeId>, + edges_map: FxHashMap<(NodeId, NodeId, Option<DomainId>), EdgeId>, + node_info: DenseMap<NodeId, Option<&'static str>>, + node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>, +} + +#[allow(clippy::new_without_default)] +impl<'a, V> ConstraintGraphBuilder<'a, V> +where + V: ValueNode, +{ + pub fn new() -> Self { + Self { + domain: DenseMap::new(), + nodes: DenseMap::new(), + edges: DenseMap::new(), + domain_identifier_map: FxHashMap::default(), + value_map: FxHashMap::default(), + edges_map: FxHashMap::default(), + node_info: DenseMap::new(), + node_metadata: DenseMap::new(), + } + } + + pub fn build(self) -> ConstraintGraph<'a, V> { + ConstraintGraph { + domain: self.domain, + domain_identifier_map: self.domain_identifier_map, + nodes: self.nodes, + edges: self.edges, + value_map: self.value_map, + node_info: self.node_info, + node_metadata: self.node_metadata, + } + } + + fn retrieve_domain_from_identifier( + &self, + domain_ident: DomainIdentifier<'_>, + ) -> Result<DomainId, GraphError<V>> { + self.domain_identifier_map + .get(&domain_ident) + .copied() + .ok_or(GraphError::DomainNotFound) + } + + pub fn make_domain( + &mut self, + domain_identifier: &'a str, + domain_description: &str, + ) -> Result<DomainId, GraphError<V>> { + let domain_identifier = DomainIdentifier::new(domain_identifier); + Ok(self + .domain_identifier_map + .clone() + .get(&domain_identifier) + .map_or_else( + || { + let domain_id = self.domain.push(DomainInfo { + domain_identifier, + domain_description: domain_description.to_string(), + }); + self.domain_identifier_map + .insert(domain_identifier, domain_id); + domain_id + }, + |domain_id| *domain_id, + )) + } + + pub fn make_value_node<M: Metadata>( + &mut self, + value: NodeValue<V>, + info: Option<&'static str>, + metadata: Option<M>, + ) -> NodeId { + self.value_map.get(&value).copied().unwrap_or_else(|| { + let node_id = self.nodes.push(Node::new(NodeType::Value(value.clone()))); + let _node_info_id = self.node_info.push(info); + + let _node_metadata_id = self + .node_metadata + .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); + + self.value_map.insert(value, node_id); + node_id + }) + } + + pub fn make_edge<'short, T: Into<DomainIdOrIdentifier<'short>>>( + &mut self, + pred_id: NodeId, + succ_id: NodeId, + strength: Strength, + relation: Relation, + domain: Option<T>, + ) -> Result<EdgeId, GraphError<V>> { + self.ensure_node_exists(pred_id)?; + self.ensure_node_exists(succ_id)?; + let domain_id = domain + .map(|d| match d.into() { + DomainIdOrIdentifier::DomainIdentifier(ident) => { + self.retrieve_domain_from_identifier(ident) + } + DomainIdOrIdentifier::DomainId(domain_id) => { + self.ensure_domain_exists(domain_id).map(|_| domain_id) + } + }) + .transpose()?; + self.edges_map + .get(&(pred_id, succ_id, domain_id)) + .copied() + .and_then(|edge_id| self.edges.get(edge_id).cloned().map(|edge| (edge_id, edge))) + .map_or_else( + || { + let edge_id = self.edges.push(Edge { + strength, + relation, + pred: pred_id, + succ: succ_id, + domain: domain_id, + }); + self.edges_map + .insert((pred_id, succ_id, domain_id), edge_id); + + let pred = self + .nodes + .get_mut(pred_id) + .ok_or(GraphError::NodeNotFound)?; + pred.succs.push(edge_id); + + let succ = self + .nodes + .get_mut(succ_id) + .ok_or(GraphError::NodeNotFound)?; + succ.preds.push(edge_id); + + Ok(edge_id) + }, + |(edge_id, edge)| { + if edge.strength == strength && edge.relation == relation { + Ok(edge_id) + } else { + Err(GraphError::ConflictingEdgeCreated) + } + }, + ) + } + + pub fn make_all_aggregator<M: Metadata>( + &mut self, + nodes: &[(NodeId, Relation, Strength)], + info: Option<&'static str>, + metadata: Option<M>, + domain: Option<&str>, + ) -> Result<NodeId, GraphError<V>> { + nodes + .iter() + .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; + + let aggregator_id = self.nodes.push(Node::new(NodeType::AllAggregator)); + let _aggregator_info_id = self.node_info.push(info); + + let _node_metadata_id = self + .node_metadata + .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); + + for (node_id, relation, strength) in nodes { + self.make_edge(*node_id, aggregator_id, *strength, *relation, domain)?; + } + + Ok(aggregator_id) + } + + pub fn make_any_aggregator<M: Metadata>( + &mut self, + nodes: &[(NodeId, Relation, Strength)], + info: Option<&'static str>, + metadata: Option<M>, + domain: Option<&str>, + ) -> Result<NodeId, GraphError<V>> { + nodes + .iter() + .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; + + let aggregator_id = self.nodes.push(Node::new(NodeType::AnyAggregator)); + let _aggregator_info_id = self.node_info.push(info); + + let _node_metadata_id = self + .node_metadata + .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); + + for (node_id, relation, strength) in nodes { + self.make_edge(*node_id, aggregator_id, *strength, *relation, domain)?; + } + + Ok(aggregator_id) + } + + pub fn make_in_aggregator<M: Metadata>( + &mut self, + values: Vec<V>, + info: Option<&'static str>, + metadata: Option<M>, + ) -> Result<NodeId, GraphError<V>> { + let key = values + .first() + .ok_or(GraphError::NoInAggregatorValues)? + .get_key(); + + for val in &values { + if val.get_key() != key { + Err(GraphError::MalformedGraph { + reason: "Values for 'In' aggregator not of same key".to_string(), + })?; + } + } + let node_id = self + .nodes + .push(Node::new(NodeType::InAggregator(FxHashSet::from_iter( + values, + )))); + let _aggregator_info_id = self.node_info.push(info); + + let _node_metadata_id = self + .node_metadata + .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); + + Ok(node_id) + } + + fn ensure_node_exists(&self, id: NodeId) -> Result<(), GraphError<V>> { + if self.nodes.contains_key(id) { + Ok(()) + } else { + Err(GraphError::NodeNotFound) + } + } + + fn ensure_domain_exists(&self, id: DomainId) -> Result<(), GraphError<V>> { + if self.domain.contains_key(id) { + Ok(()) + } else { + Err(GraphError::DomainNotFound) + } + } +} diff --git a/crates/euclid/src/utils/dense_map.rs b/crates/hyperswitch_constraint_graph/src/dense_map.rs similarity index 92% rename from crates/euclid/src/utils/dense_map.rs rename to crates/hyperswitch_constraint_graph/src/dense_map.rs index 8bd4487c77b..682833d65e6 100644 --- a/crates/euclid/src/utils/dense_map.rs +++ b/crates/hyperswitch_constraint_graph/src/dense_map.rs @@ -5,6 +5,24 @@ pub trait EntityId { fn with_id(id: usize) -> Self; } +macro_rules! impl_entity { + ($name:ident) => { + impl $crate::dense_map::EntityId for $name { + #[inline] + fn get_id(&self) -> usize { + self.0 + } + + #[inline] + fn with_id(id: usize) -> Self { + Self(id) + } + } + }; +} + +pub(crate) use impl_entity; + pub struct DenseMap<K, V> { data: Vec<V>, _marker: PhantomData<K>, diff --git a/crates/hyperswitch_constraint_graph/src/error.rs b/crates/hyperswitch_constraint_graph/src/error.rs new file mode 100644 index 00000000000..cd2269de264 --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/error.rs @@ -0,0 +1,77 @@ +use std::sync::{Arc, Weak}; + +use crate::types::{Metadata, NodeValue, Relation, RelationResolution, ValueNode}; + +#[derive(Debug, Clone, serde::Serialize)] +#[serde(tag = "type", content = "predecessor", rename_all = "snake_case")] +pub enum ValueTracePredecessor<V: ValueNode> { + Mandatory(Box<Weak<AnalysisTrace<V>>>), + OneOf(Vec<Weak<AnalysisTrace<V>>>), +} + +#[derive(Debug, Clone, serde::Serialize)] +#[serde(tag = "type", content = "trace", rename_all = "snake_case")] +pub enum AnalysisTrace<V: ValueNode> { + Value { + value: NodeValue<V>, + relation: Relation, + predecessors: Option<ValueTracePredecessor<V>>, + info: Option<&'static str>, + metadata: Option<Arc<dyn Metadata>>, + }, + + AllAggregation { + unsatisfied: Vec<Weak<AnalysisTrace<V>>>, + info: Option<&'static str>, + metadata: Option<Arc<dyn Metadata>>, + }, + + AnyAggregation { + unsatisfied: Vec<Weak<AnalysisTrace<V>>>, + info: Option<&'static str>, + metadata: Option<Arc<dyn Metadata>>, + }, + + InAggregation { + expected: Vec<V>, + found: Option<V>, + relation: Relation, + info: Option<&'static str>, + metadata: Option<Arc<dyn Metadata>>, + }, + Contradiction { + relation: RelationResolution, + }, +} + +#[derive(Debug, Clone, serde::Serialize, thiserror::Error)] +#[serde(tag = "type", content = "info", rename_all = "snake_case")] +pub enum GraphError<V: ValueNode> { + #[error("An edge was not found in the graph")] + EdgeNotFound, + #[error("Attempted to create a conflicting edge between two nodes")] + ConflictingEdgeCreated, + #[error("Cycle detected in graph")] + CycleDetected, + #[error("Domain wasn't found in the Graph")] + DomainNotFound, + #[error("Malformed Graph: {reason}")] + MalformedGraph { reason: String }, + #[error("A node was not found in the graph")] + NodeNotFound, + #[error("A value node was not found: {0:#?}")] + ValueNodeNotFound(V), + #[error("No values provided for an 'in' aggregator node")] + NoInAggregatorValues, + #[error("Error during analysis: {0:#?}")] + AnalysisError(Weak<AnalysisTrace<V>>), +} + +impl<V: ValueNode> GraphError<V> { + pub fn get_analysis_trace(self) -> Result<Weak<AnalysisTrace<V>>, Self> { + match self { + Self::AnalysisError(trace) => Ok(trace), + _ => Err(self), + } + } +} diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rs new file mode 100644 index 00000000000..d0a98e19520 --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/graph.rs @@ -0,0 +1,587 @@ +use std::sync::{Arc, Weak}; + +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{ + builder, + dense_map::DenseMap, + error::{self, AnalysisTrace, GraphError}, + types::{ + CheckingContext, CycleCheck, DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, + Memoization, Metadata, Node, NodeId, NodeType, NodeValue, Relation, RelationResolution, + Strength, ValueNode, + }, +}; + +struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> { + ctx: &'a C, + node: &'a Node<V>, + node_id: NodeId, + relation: Relation, + strength: Strength, + memo: &'a mut Memoization<V>, + cycle_map: &'a mut CycleCheck, + domains: Option<&'a [DomainId]>, +} + +pub struct ConstraintGraph<'a, V: ValueNode> { + pub domain: DenseMap<DomainId, DomainInfo<'a>>, + pub domain_identifier_map: FxHashMap<DomainIdentifier<'a>, DomainId>, + pub nodes: DenseMap<NodeId, Node<V>>, + pub edges: DenseMap<EdgeId, Edge>, + pub value_map: FxHashMap<NodeValue<V>, NodeId>, + pub node_info: DenseMap<NodeId, Option<&'static str>>, + pub node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>, +} + +impl<'a, V> ConstraintGraph<'a, V> +where + V: ValueNode, +{ + fn get_predecessor_edges_by_domain( + &self, + node_id: NodeId, + domains: Option<&[DomainId]>, + ) -> Result<Vec<&Edge>, GraphError<V>> { + let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; + let mut final_list = Vec::new(); + for &pred in &node.preds { + let edge = self.edges.get(pred).ok_or(GraphError::EdgeNotFound)?; + if let Some((domain_id, domains)) = edge.domain.zip(domains) { + if domains.contains(&domain_id) { + final_list.push(edge); + } + } else if edge.domain.is_none() { + final_list.push(edge); + } + } + + Ok(final_list) + } + + #[allow(clippy::too_many_arguments)] + pub fn check_node<C>( + &self, + ctx: &C, + node_id: NodeId, + relation: Relation, + strength: Strength, + memo: &mut Memoization<V>, + cycle_map: &mut CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let domains = domains + .map(|domain_idents| { + domain_idents + .iter() + .map(|domain_ident| { + self.domain_identifier_map + .get(&DomainIdentifier::new(domain_ident)) + .copied() + .ok_or(GraphError::DomainNotFound) + }) + .collect::<Result<Vec<_>, _>>() + }) + .transpose()?; + + self.check_node_inner( + ctx, + node_id, + relation, + strength, + memo, + cycle_map, + domains.as_deref(), + ) + } + + #[allow(clippy::too_many_arguments)] + pub fn check_node_inner<C>( + &self, + ctx: &C, + node_id: NodeId, + relation: Relation, + strength: Strength, + memo: &mut Memoization<V>, + cycle_map: &mut CycleCheck, + domains: Option<&[DomainId]>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; + + if let Some(already_memo) = memo.get(&(node_id, relation, strength)) { + already_memo + .clone() + .map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err))) + } else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).cloned() + { + let strength_relation = Strength::get_resolved_strength(initial_strength, strength); + let relation_resolve = + RelationResolution::get_resolved_relation(initial_relation, relation.into()); + cycle_map.entry(node_id).and_modify(|value| { + value.0 = strength_relation; + value.1 = relation_resolve + }); + Ok(()) + } else { + let check_node_context = CheckNodeContext { + node, + node_id, + relation, + strength, + memo, + cycle_map, + ctx, + domains, + }; + match &node.node_type { + NodeType::AllAggregator => self.validate_all_aggregator(check_node_context), + + NodeType::AnyAggregator => self.validate_any_aggregator(check_node_context), + + NodeType::InAggregator(expected) => { + self.validate_in_aggregator(check_node_context, expected) + } + NodeType::Value(val) => self.validate_value_node(check_node_context, val), + } + } + } + + fn validate_all_aggregator<C>( + &self, + vald: CheckNodeContext<'_, V, C>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new(); + + for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { + vald.cycle_map + .insert(vald.node_id, (vald.strength, vald.relation.into())); + if let Err(e) = self.check_node_inner( + vald.ctx, + edge.pred, + edge.relation, + edge.strength, + vald.memo, + vald.cycle_map, + vald.domains, + ) { + unsatisfied.push(e.get_analysis_trace()?); + } + if let Some((_resolved_strength, resolved_relation)) = + vald.cycle_map.remove(&vald.node_id) + { + if resolved_relation == RelationResolution::Contradiction { + let err = Arc::new(AnalysisTrace::Contradiction { + relation: resolved_relation, + }); + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + return Err(GraphError::AnalysisError(Arc::downgrade(&err))); + } + } + } + + if !unsatisfied.is_empty() { + let err = Arc::new(AnalysisTrace::AllAggregation { + unsatisfied, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err))) + } else { + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } + } + + fn validate_any_aggregator<C>( + &self, + vald: CheckNodeContext<'_, V, C>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new(); + let mut matched_one = false; + + for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { + vald.cycle_map + .insert(vald.node_id, (vald.strength, vald.relation.into())); + if let Err(e) = self.check_node_inner( + vald.ctx, + edge.pred, + edge.relation, + edge.strength, + vald.memo, + vald.cycle_map, + vald.domains, + ) { + unsatisfied.push(e.get_analysis_trace()?); + } else { + matched_one = true; + } + if let Some((_resolved_strength, resolved_relation)) = + vald.cycle_map.remove(&vald.node_id) + { + if resolved_relation == RelationResolution::Contradiction { + let err = Arc::new(AnalysisTrace::Contradiction { + relation: resolved_relation, + }); + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + + return Err(GraphError::AnalysisError(Arc::downgrade(&err))); + } + } + } + + if matched_one || vald.node.preds.is_empty() { + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } else { + let err = Arc::new(AnalysisTrace::AnyAggregation { + unsatisfied: unsatisfied.clone(), + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err))) + } + } + + fn validate_in_aggregator<C>( + &self, + vald: CheckNodeContext<'_, V, C>, + expected: &FxHashSet<V>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let the_key = expected + .iter() + .next() + .ok_or_else(|| GraphError::MalformedGraph { + reason: "An OnlyIn aggregator node must have at least one expected value" + .to_string(), + })? + .get_key(); + + let ctx_vals = if let Some(vals) = vald.ctx.get_values_by_key(&the_key) { + vals + } else { + return if let Strength::Weak = vald.strength { + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } else { + let err = Arc::new(AnalysisTrace::InAggregation { + expected: expected.iter().cloned().collect(), + found: None, + relation: vald.relation, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err))) + }; + }; + + let relation_bool: bool = vald.relation.into(); + for ctx_value in ctx_vals { + if expected.contains(&ctx_value) != relation_bool { + let err = Arc::new(AnalysisTrace::InAggregation { + expected: expected.iter().cloned().collect(), + found: Some(ctx_value.clone()), + relation: vald.relation, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; + } + } + + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } + + fn validate_value_node<C>( + &self, + vald: CheckNodeContext<'_, V, C>, + val: &NodeValue<V>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let mut errors = Vec::<Weak<AnalysisTrace<V>>>::new(); + let mut matched_one = false; + + self.context_analysis( + vald.node_id, + vald.relation, + vald.strength, + vald.ctx, + val, + vald.memo, + )?; + + for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { + vald.cycle_map + .insert(vald.node_id, (vald.strength, vald.relation.into())); + let result = self.check_node_inner( + vald.ctx, + edge.pred, + edge.relation, + edge.strength, + vald.memo, + vald.cycle_map, + vald.domains, + ); + + if let Some((resolved_strength, resolved_relation)) = + vald.cycle_map.remove(&vald.node_id) + { + if resolved_relation == RelationResolution::Contradiction { + let err = Arc::new(AnalysisTrace::Contradiction { + relation: resolved_relation, + }); + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + return Err(GraphError::AnalysisError(Arc::downgrade(&err))); + } else if resolved_strength != vald.strength { + self.context_analysis( + vald.node_id, + vald.relation, + resolved_strength, + vald.ctx, + val, + vald.memo, + )? + } + } + match (edge.strength, result) { + (Strength::Strong, Err(trace)) => { + let err = Arc::new(AnalysisTrace::Value { + value: val.clone(), + relation: vald.relation, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + predecessors: Some(error::ValueTracePredecessor::Mandatory(Box::new( + trace.get_analysis_trace()?, + ))), + }); + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; + } + + (Strength::Strong, Ok(_)) => { + matched_one = true; + } + + (Strength::Normal | Strength::Weak, Err(trace)) => { + errors.push(trace.get_analysis_trace()?); + } + + (Strength::Normal | Strength::Weak, Ok(_)) => { + matched_one = true; + } + } + } + + if matched_one || vald.node.preds.is_empty() { + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } else { + let err = Arc::new(AnalysisTrace::Value { + value: val.clone(), + relation: vald.relation, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + predecessors: Some(error::ValueTracePredecessor::OneOf(errors.clone())), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err))) + } + } + + fn context_analysis<C>( + &self, + node_id: NodeId, + relation: Relation, + strength: Strength, + ctx: &C, + val: &NodeValue<V>, + memo: &mut Memoization<V>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let in_context = ctx.check_presence(val, strength); + let relation_bool: bool = relation.into(); + if in_context != relation_bool { + let err = Arc::new(AnalysisTrace::Value { + value: val.clone(), + relation, + predecessors: None, + info: self.node_info.get(node_id).cloned().flatten(), + metadata: self.node_metadata.get(node_id).cloned().flatten(), + }); + memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); + Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; + } + if !relation_bool { + memo.insert((node_id, relation, strength), Ok(())); + return Ok(()); + } + Ok(()) + } + + pub fn combine<'b>(g1: &'b Self, g2: &'b Self) -> Result<Self, GraphError<V>> { + let mut node_builder = builder::ConstraintGraphBuilder::new(); + let mut g1_old2new_id = DenseMap::<NodeId, NodeId>::new(); + let mut g2_old2new_id = DenseMap::<NodeId, NodeId>::new(); + let mut g1_old2new_domain_id = DenseMap::<DomainId, DomainId>::new(); + let mut g2_old2new_domain_id = DenseMap::<DomainId, DomainId>::new(); + + let add_domain = |node_builder: &mut builder::ConstraintGraphBuilder<'a, V>, + domain: DomainInfo<'a>| + -> Result<DomainId, GraphError<V>> { + node_builder.make_domain( + domain.domain_identifier.into_inner(), + &domain.domain_description, + ) + }; + + let add_node = |node_builder: &mut builder::ConstraintGraphBuilder<'a, V>, + node: &Node<V>| + -> Result<NodeId, GraphError<V>> { + match &node.node_type { + NodeType::Value(node_value) => { + Ok(node_builder.make_value_node(node_value.clone(), None, None::<()>)) + } + + NodeType::AllAggregator => { + Ok(node_builder.make_all_aggregator(&[], None, None::<()>, None)?) + } + + NodeType::AnyAggregator => { + Ok(node_builder.make_any_aggregator(&[], None, None::<()>, None)?) + } + + NodeType::InAggregator(expected) => Ok(node_builder.make_in_aggregator( + expected.iter().cloned().collect(), + None, + None::<()>, + )?), + } + }; + + for (_old_domain_id, domain) in g1.domain.iter() { + let new_domain_id = add_domain(&mut node_builder, domain.clone())?; + g1_old2new_domain_id.push(new_domain_id); + } + + for (_old_domain_id, domain) in g2.domain.iter() { + let new_domain_id = add_domain(&mut node_builder, domain.clone())?; + g2_old2new_domain_id.push(new_domain_id); + } + + for (_old_node_id, node) in g1.nodes.iter() { + let new_node_id = add_node(&mut node_builder, node)?; + g1_old2new_id.push(new_node_id); + } + + for (_old_node_id, node) in g2.nodes.iter() { + let new_node_id = add_node(&mut node_builder, node)?; + g2_old2new_id.push(new_node_id); + } + + for edge in g1.edges.values() { + let new_pred_id = g1_old2new_id + .get(edge.pred) + .ok_or(GraphError::NodeNotFound)?; + let new_succ_id = g1_old2new_id + .get(edge.succ) + .ok_or(GraphError::NodeNotFound)?; + let domain_ident = edge + .domain + .map(|domain_id| g1.domain.get(domain_id).ok_or(GraphError::DomainNotFound)) + .transpose()? + .map(|domain| domain.domain_identifier); + + node_builder.make_edge( + *new_pred_id, + *new_succ_id, + edge.strength, + edge.relation, + domain_ident.as_deref(), + )?; + } + + for edge in g2.edges.values() { + let new_pred_id = g2_old2new_id + .get(edge.pred) + .ok_or(GraphError::NodeNotFound)?; + let new_succ_id = g2_old2new_id + .get(edge.succ) + .ok_or(GraphError::NodeNotFound)?; + let domain_ident = edge + .domain + .map(|domain_id| g2.domain.get(domain_id).ok_or(GraphError::DomainNotFound)) + .transpose()? + .map(|domain| domain.domain_identifier); + + node_builder.make_edge( + *new_pred_id, + *new_succ_id, + edge.strength, + edge.relation, + domain_ident.as_deref(), + )?; + } + + Ok(node_builder.build()) + } +} diff --git a/crates/hyperswitch_constraint_graph/src/lib.rs b/crates/hyperswitch_constraint_graph/src/lib.rs new file mode 100644 index 00000000000..ade9a64272f --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/lib.rs @@ -0,0 +1,13 @@ +pub mod builder; +mod dense_map; +pub mod error; +pub mod graph; +pub mod types; + +pub use builder::ConstraintGraphBuilder; +pub use error::{AnalysisTrace, GraphError}; +pub use graph::ConstraintGraph; +pub use types::{ + CheckingContext, CycleCheck, DomainId, DomainIdentifier, Edge, EdgeId, KeyNode, Memoization, + Node, NodeId, NodeValue, Relation, Strength, ValueNode, +}; diff --git a/crates/hyperswitch_constraint_graph/src/types.rs b/crates/hyperswitch_constraint_graph/src/types.rs new file mode 100644 index 00000000000..d1d14bd7e5c --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/types.rs @@ -0,0 +1,249 @@ +use std::{ + any::Any, + fmt, hash, + ops::{Deref, DerefMut}, + sync::Arc, +}; + +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{dense_map::impl_entity, error::AnalysisTrace}; + +pub trait KeyNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq {} + +pub trait ValueNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq { + type Key: KeyNode; + + fn get_key(&self) -> Self::Key; +} + +#[derive(Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash)] +#[serde(transparent)] +pub struct NodeId(usize); + +impl_entity!(NodeId); + +#[derive(Debug)] +pub struct Node<V: ValueNode> { + pub node_type: NodeType<V>, + pub preds: Vec<EdgeId>, + pub succs: Vec<EdgeId>, +} + +impl<V: ValueNode> Node<V> { + pub(crate) fn new(node_type: NodeType<V>) -> Self { + Self { + node_type, + preds: Vec::new(), + succs: Vec::new(), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum NodeType<V: ValueNode> { + AllAggregator, + AnyAggregator, + InAggregator(FxHashSet<V>), + Value(NodeValue<V>), +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)] +#[serde(tag = "type", content = "value", rename_all = "snake_case")] +pub enum NodeValue<V: ValueNode> { + Key(<V as ValueNode>::Key), + Value(V), +} + +impl<V: ValueNode> From<V> for NodeValue<V> { + fn from(value: V) -> Self { + Self::Value(value) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct EdgeId(usize); + +impl_entity!(EdgeId); + +#[derive( + Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash, strum::Display, PartialOrd, Ord, +)] +pub enum Strength { + Weak, + Normal, + Strong, +} + +impl Strength { + pub fn get_resolved_strength(prev_strength: Self, curr_strength: Self) -> Self { + std::cmp::max(prev_strength, curr_strength) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Relation { + Positive, + Negative, +} + +impl From<Relation> for bool { + fn from(value: Relation) -> Self { + matches!(value, Relation::Positive) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)] +pub enum RelationResolution { + Positive, + Negative, + Contradiction, +} + +impl From<Relation> for RelationResolution { + fn from(value: Relation) -> Self { + match value { + Relation::Positive => Self::Positive, + Relation::Negative => Self::Negative, + } + } +} + +impl RelationResolution { + pub fn get_resolved_relation(prev_relation: Self, curr_relation: Self) -> Self { + if prev_relation != curr_relation { + Self::Contradiction + } else { + curr_relation + } + } +} + +#[derive(Debug, Clone)] +pub struct Edge { + pub strength: Strength, + pub relation: Relation, + pub pred: NodeId, + pub succ: NodeId, + pub domain: Option<DomainId>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct DomainId(usize); + +impl_entity!(DomainId); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct DomainIdentifier<'a>(&'a str); + +impl<'a> DomainIdentifier<'a> { + pub fn new(identifier: &'a str) -> Self { + Self(identifier) + } + + pub fn into_inner(&self) -> &'a str { + self.0 + } +} + +impl<'a> From<&'a str> for DomainIdentifier<'a> { + fn from(value: &'a str) -> Self { + Self(value) + } +} + +impl<'a> Deref for DomainIdentifier<'a> { + type Target = str; + + fn deref(&self) -> &'a Self::Target { + self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct DomainInfo<'a> { + pub domain_identifier: DomainIdentifier<'a>, + pub domain_description: String, +} + +pub trait CheckingContext { + type Value: ValueNode; + + fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self + where + L: Into<Self::Value>; + + fn check_presence(&self, value: &NodeValue<Self::Value>, strength: Strength) -> bool; + + fn get_values_by_key( + &self, + expected: &<Self::Value as ValueNode>::Key, + ) -> Option<Vec<Self::Value>>; +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct Memoization<V: ValueNode>( + #[allow(clippy::type_complexity)] + FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>, +); + +impl<V: ValueNode> Memoization<V> { + pub fn new() -> Self { + Self(FxHashMap::default()) + } +} + +impl<V: ValueNode> Default for Memoization<V> { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl<V: ValueNode> Deref for Memoization<V> { + type Target = FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<V: ValueNode> DerefMut for Memoization<V> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +#[derive(Debug, Clone)] +pub struct CycleCheck(FxHashMap<NodeId, (Strength, RelationResolution)>); +impl CycleCheck { + pub fn new() -> Self { + Self(FxHashMap::default()) + } +} + +impl Default for CycleCheck { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl Deref for CycleCheck { + type Target = FxHashMap<NodeId, (Strength, RelationResolution)>; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for CycleCheck { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +pub trait Metadata: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {} +erased_serde::serialize_trait_object!(Metadata); + +impl<M> Metadata for M where M: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {} diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index 4ad5ef04f42..86de6002c32 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -13,6 +13,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } common_enums = { version = "0.1.0", path = "../common_enums" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } euclid = { version = "0.1.0", path = "../euclid" } masking = { version = "0.1.0", path = "../masking/" } diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs index 6105dc85d7e..9921ee7af35 100644 --- a/crates/kgraph_utils/benches/evaluation.rs +++ b/crates/kgraph_utils/benches/evaluation.rs @@ -8,13 +8,17 @@ use api_models::{ use criterion::{black_box, criterion_group, criterion_main, Criterion}; use euclid::{ dirval, - dssa::graph::{self, Memoization}, + dssa::graph::{self, CgraphExt}, frontend::dir, types::{NumValue, NumValueRefinement}, }; +use hyperswitch_constraint_graph::{CycleCheck, Memoization}; use kgraph_utils::{error::KgraphError, transformers::IntoDirValue}; -fn build_test_data<'a>(total_enabled: usize, total_pm_types: usize) -> graph::KnowledgeGraph<'a> { +fn build_test_data<'a>( + total_enabled: usize, + total_pm_types: usize, +) -> hyperswitch_constraint_graph::ConstraintGraph<'a, dir::DirValue> { use api_models::{admin::*, payment_methods::*}; let mut pms_enabled: Vec<PaymentMethodsEnabled> = Vec::new(); @@ -88,6 +92,8 @@ fn evaluation(c: &mut Criterion) { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); }); }); @@ -105,6 +111,8 @@ fn evaluation(c: &mut Criterion) { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); }); }); diff --git a/crates/kgraph_utils/src/error.rs b/crates/kgraph_utils/src/error.rs index 5a16c6375b0..95450fbe350 100644 --- a/crates/kgraph_utils/src/error.rs +++ b/crates/kgraph_utils/src/error.rs @@ -1,4 +1,4 @@ -use euclid::dssa::{graph::GraphError, types::AnalysisErrorType}; +use euclid::{dssa::types::AnalysisErrorType, frontend::dir}; #[derive(Debug, thiserror::Error, serde::Serialize)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] @@ -6,7 +6,7 @@ pub enum KgraphError { #[error("Invalid connector name encountered: '{0}'")] InvalidConnectorName(String), #[error("There was an error constructing the graph: {0}")] - GraphConstructionError(GraphError), + GraphConstructionError(hyperswitch_constraint_graph::GraphError<dir::DirValue>), #[error("There was an error constructing the context")] ContextConstructionError(AnalysisErrorType), #[error("there was an unprecedented indexing error")] diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 8542437a5a6..14a88dd1c6e 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -4,42 +4,39 @@ use api_models::{ admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes, }; use euclid::{ - dssa::graph::{self, DomainIdentifier}, frontend::{ast, dir}, types::{NumValue, NumValueRefinement}, }; +use hyperswitch_constraint_graph as cgraph; use crate::{error::KgraphError, transformers::IntoDirValue}; pub const DOMAIN_IDENTIFIER: &str = "payment_methods_enabled_for_merchantconnectoraccount"; fn compile_request_pm_types( - builder: &mut graph::KnowledgeGraphBuilder<'_>, + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, pm_types: RequestPaymentMethodTypes, pm: api_enums::PaymentMethod, -) -> Result<graph::NodeId, KgraphError> { - let mut agg_nodes: Vec<(graph::NodeId, graph::Relation, graph::Strength)> = Vec::new(); +) -> Result<cgraph::NodeId, KgraphError> { + let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let pmt_info = "PaymentMethodType"; - let pmt_id = builder - .make_value_node( - (pm_types.payment_method_type, pm) - .into_dir_value() - .map(Into::into)?, - Some(pmt_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let pmt_id = builder.make_value_node( + (pm_types.payment_method_type, pm) + .into_dir_value() + .map(Into::into)?, + Some(pmt_info), + None::<()>, + ); agg_nodes.push(( pmt_id, - graph::Relation::Positive, + cgraph::Relation::Positive, match pm_types.payment_method_type { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { - graph::Strength::Weak + cgraph::Strength::Weak } - _ => graph::Strength::Strong, + _ => cgraph::Strength::Strong, }, )); @@ -52,13 +49,13 @@ fn compile_request_pm_types( let card_network_info = "Card Networks"; let card_network_id = builder - .make_in_aggregator(dir_vals, Some(card_network_info), None::<()>, Vec::new()) + .make_in_aggregator(dir_vals, Some(card_network_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( card_network_id, - graph::Relation::Positive, - graph::Strength::Weak, + cgraph::Relation::Positive, + cgraph::Strength::Weak, )); } } @@ -71,7 +68,7 @@ fn compile_request_pm_types( .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, - graph::Relation::Positive, + cgraph::Relation::Positive, )), admin_api::AcceptedCurrencies::DisableOnly(curr) if !curr.is_empty() => Some(( @@ -79,7 +76,7 @@ fn compile_request_pm_types( .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, - graph::Relation::Negative, + cgraph::Relation::Negative, )), _ => None, @@ -88,15 +85,10 @@ fn compile_request_pm_types( if let Some((currencies, relation)) = currencies_data { let accepted_currencies_info = "Accepted Currencies"; let accepted_currencies_id = builder - .make_in_aggregator( - currencies, - Some(accepted_currencies_info), - None::<()>, - Vec::new(), - ) + .make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; - agg_nodes.push((accepted_currencies_id, relation, graph::Strength::Strong)); + agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong)); } let mut amount_nodes = Vec::with_capacity(2); @@ -108,14 +100,11 @@ fn compile_request_pm_types( }; let min_amt_info = "Minimum Amount"; - let min_amt_id = builder - .make_value_node( - dir::DirValue::PaymentAmount(num_val).into(), - Some(min_amt_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let min_amt_id = builder.make_value_node( + dir::DirValue::PaymentAmount(num_val).into(), + Some(min_amt_info), + None::<()>, + ); amount_nodes.push(min_amt_id); } @@ -127,14 +116,11 @@ fn compile_request_pm_types( }; let max_amt_info = "Maximum Amount"; - let max_amt_id = builder - .make_value_node( - dir::DirValue::PaymentAmount(num_val).into(), - Some(max_amt_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let max_amt_id = builder.make_value_node( + dir::DirValue::PaymentAmount(num_val).into(), + Some(max_amt_info), + None::<()>, + ); amount_nodes.push(max_amt_id); } @@ -145,14 +131,11 @@ fn compile_request_pm_types( refinement: None, }; - let zero_amt_id = builder - .make_value_node( - dir::DirValue::PaymentAmount(zero_num_val).into(), - Some("zero_amount"), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let zero_amt_id = builder.make_value_node( + dir::DirValue::PaymentAmount(zero_num_val).into(), + Some("zero_amount"), + None::<()>, + ); let or_node_neighbor_id = if amount_nodes.len() == 1 { amount_nodes @@ -163,7 +146,13 @@ fn compile_request_pm_types( let nodes = amount_nodes .iter() .copied() - .map(|node_id| (node_id, graph::Relation::Positive, graph::Strength::Strong)) + .map(|node_id| { + ( + node_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + ) + }) .collect::<Vec<_>>(); builder @@ -171,7 +160,7 @@ fn compile_request_pm_types( &nodes, Some("amount_constraint_aggregator"), None::<()>, - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], + None, ) .map_err(KgraphError::GraphConstructionError)? }; @@ -179,37 +168,40 @@ fn compile_request_pm_types( let any_aggregator = builder .make_any_aggregator( &[ - (zero_amt_id, graph::Relation::Positive), - (or_node_neighbor_id, graph::Relation::Positive), + ( + zero_amt_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + ), + ( + or_node_neighbor_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + ), ], Some("zero_plus_limits_amount_aggregator"), None::<()>, - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], + None, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( any_aggregator, - graph::Relation::Positive, - graph::Strength::Strong, + cgraph::Relation::Positive, + cgraph::Strength::Strong, )); } let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType"; builder - .make_all_aggregator( - &agg_nodes, - Some(pmt_all_aggregator_info), - None::<()>, - Vec::new(), - ) + .make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError) } fn compile_payment_method_enabled( - builder: &mut graph::KnowledgeGraphBuilder<'_>, + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, enabled: admin_api::PaymentMethodsEnabled, -) -> Result<Option<graph::NodeId>, KgraphError> { +) -> Result<Option<cgraph::NodeId>, KgraphError> { let agg_id = if !enabled .payment_method_types .as_ref() @@ -217,48 +209,44 @@ fn compile_payment_method_enabled( .unwrap_or(true) { let pm_info = "PaymentMethod"; - let pm_id = builder - .make_value_node( - enabled.payment_method.into_dir_value().map(Into::into)?, - Some(pm_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let pm_id = builder.make_value_node( + enabled.payment_method.into_dir_value().map(Into::into)?, + Some(pm_info), + None::<()>, + ); - let mut agg_nodes: Vec<(graph::NodeId, graph::Relation)> = Vec::new(); + let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pm_types) = enabled.payment_method_types { for pm_type in pm_types { let node_id = compile_request_pm_types(builder, pm_type, enabled.payment_method)?; - agg_nodes.push((node_id, graph::Relation::Positive)); + agg_nodes.push(( + node_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + )); } } let any_aggregator_info = "Any aggregation for PaymentMethodsType"; let pm_type_agg_id = builder - .make_any_aggregator( - &agg_nodes, - Some(any_aggregator_info), - None::<()>, - Vec::new(), - ) + .make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let all_aggregator_info = "All aggregation for PaymentMethod"; let enabled_pm_agg_id = builder .make_all_aggregator( &[ - (pm_id, graph::Relation::Positive, graph::Strength::Strong), + (pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong), ( pm_type_agg_id, - graph::Relation::Positive, - graph::Strength::Strong, + cgraph::Relation::Positive, + cgraph::Strength::Strong, ), ], Some(all_aggregator_info), None::<()>, - Vec::new(), + None, ) .map_err(KgraphError::GraphConstructionError)?; @@ -271,26 +259,30 @@ fn compile_payment_method_enabled( } fn compile_merchant_connector_graph( - builder: &mut graph::KnowledgeGraphBuilder<'_>, + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, mca: admin_api::MerchantConnectorResponse, ) -> Result<(), KgraphError> { let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name) .map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?; - let mut agg_nodes: Vec<(graph::NodeId, graph::Relation)> = Vec::new(); + let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pms_enabled) = mca.payment_methods_enabled { for pm_enabled in pms_enabled { let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?; if let Some(pm_enabled_id) = maybe_pm_enabled_id { - agg_nodes.push((pm_enabled_id, graph::Relation::Positive)); + agg_nodes.push(( + pm_enabled_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + )); } } } let aggregator_info = "Available Payment methods for connector"; let pms_enabled_agg_id = builder - .make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, Vec::new()) + .make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { @@ -300,21 +292,16 @@ fn compile_merchant_connector_graph( })); let connector_info = "Connector"; - let connector_node_id = builder - .make_value_node( - connector_dir_val.into(), - Some(connector_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let connector_node_id = + builder.make_value_node(connector_dir_val.into(), Some(connector_info), None::<()>); builder .make_edge( pms_enabled_agg_id, connector_node_id, - graph::Strength::Normal, - graph::Relation::Positive, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, ) .map_err(KgraphError::GraphConstructionError)?; @@ -323,11 +310,11 @@ fn compile_merchant_connector_graph( pub fn make_mca_graph<'a>( accts: Vec<admin_api::MerchantConnectorResponse>, -) -> Result<graph::KnowledgeGraph<'a>, KgraphError> { - let mut builder = graph::KnowledgeGraphBuilder::new(); +) -> Result<cgraph::ConstraintGraph<'a, dir::DirValue>, KgraphError> { + let mut builder = cgraph::ConstraintGraphBuilder::new(); let _domain = builder.make_domain( - DomainIdentifier::new(DOMAIN_IDENTIFIER), - "Payment methods enabled for MerchantConnectorAccount".to_string(), + DOMAIN_IDENTIFIER, + "Payment methods enabled for MerchantConnectorAccount", ); for acct in accts { compile_merchant_connector_graph(&mut builder, acct)?; @@ -343,12 +330,13 @@ mod tests { use api_models::enums as api_enums; use euclid::{ dirval, - dssa::graph::{AnalysisContext, Memoization}, + dssa::graph::{AnalysisContext, CgraphExt}, }; + use hyperswitch_constraint_graph::{ConstraintGraph, CycleCheck, Memoization}; use super::*; - fn build_test_data<'a>() -> graph::KnowledgeGraph<'a> { + fn build_test_data<'a>() -> ConstraintGraph<'a, dir::DirValue> { use api_models::{admin::*, payment_methods::*}; let stripe_account = MerchantConnectorResponse { @@ -428,6 +416,8 @@ mod tests { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -448,6 +438,8 @@ mod tests { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -468,6 +460,8 @@ mod tests { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -488,6 +482,8 @@ mod tests { dirval!(PaymentAmount = 7), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -507,6 +503,8 @@ mod tests { dirval!(PaymentAmount = 7), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); //println!("{:#?}", result); @@ -529,6 +527,8 @@ mod tests { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); //println!("{:#?}", result); @@ -725,6 +725,8 @@ mod tests { dirval!(Connector = Stripe), &context, &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_ok(), "stripe validation failed"); @@ -733,6 +735,8 @@ mod tests { dirval!(Connector = Bluesnap), &context, &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_err(), "bluesnap validation failed"); } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f8e2cfad126..7ff47b927d8 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -103,6 +103,7 @@ analytics = { version = "0.1.0", path = "../analytics", optional = true } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs"] } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index ff7303c900d..6967c977753 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -17,9 +17,9 @@ use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ backend::{self, inputs as dsl_inputs, EuclidBackend}, - dssa::graph::{self as euclid_graph, Memoization}, + dssa::graph::{self as euclid_graph, CgraphExt}, enums as euclid_enums, - frontend::ast, + frontend::{ast, dir as euclid_dir}, }; use kgraph_utils::{ mca as mca_graph, @@ -82,7 +82,9 @@ pub struct SessionRoutingPmTypeInput<'a> { profile_id: Option<String>, } static ROUTING_CACHE: StaticCache<CachedAlgorithm> = StaticCache::new(); -static KGRAPH_CACHE: StaticCache<euclid_graph::KnowledgeGraph<'_>> = StaticCache::new(); +static KGRAPH_CACHE: StaticCache< + hyperswitch_constraint_graph::ConstraintGraph<'_, euclid_dir::DirValue>, +> = StaticCache::new(); type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>; @@ -542,7 +544,7 @@ pub async fn get_merchant_kgraph<'a>( merchant_last_modified: i64, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<Arc<euclid_graph::KnowledgeGraph<'a>>> { +) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<'a, euclid_dir::DirValue>>> { let merchant_id = &key_store.merchant_id; #[cfg(feature = "business_profile_routing")] @@ -690,7 +692,13 @@ async fn perform_kgraph_filtering( .into_dir_value() .change_context(errors::RoutingError::KgraphAnalysisError)?; let kgraph_eligible = cached_kgraph - .check_value_validity(dir_val, &context, &mut Memoization::new()) + .check_value_validity( + dir_val, + &context, + &mut hyperswitch_constraint_graph::Memoization::new(), + &mut hyperswitch_constraint_graph::CycleCheck::new(), + None, + ) .change_context(errors::RoutingError::KgraphAnalysisError)?; let filter_eligible =
2023-12-06T13:01:25Z
## 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 separates out and refactors the Euclid Knowledge Graph into the Constraint Graph in its own crate, and makes the Constraint Graph generic so it can work on custom key and value types as opposed to just the Euclid Key and Value types. This will remove the dependency on Euclid when one needs to only use the Constraint Graph, plus the now generic nature of Constraint Graphs will allow them to be utilized for varied use cases other than routing. ### 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). --> Making the constraint graph generic opens up the opportunity for other developers to adapt and use the constraint graph for their own usecases. There are many validation use cases currently in Hyperswitch that can be fulfilled by using Constraint Graphs, including but not limited to Connector domain validations, required field selection, etc. ## 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)? --> Unit tests for the `euclid` and `kgraph_utils` crates. No specific API tests required. Euclid: <img width="586" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/86ce0f9b-200b-4da7-903e-bf1c49d22c63"> Kgraph_utils: <img width="586" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/7fbb186d-8545-4da8-81b1-7d1f4f612d4c"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ecc97bc8684d57834f62652265316df29cf2cf5d
juspay/hyperswitch
juspay__hyperswitch-2961
Bug: Add connector enums for Routing in add_connector script [BUG] ### Bug Description Recently, routing has been moved to OSS. This change breaks the add_connector script. Connector Enums should be added in euclid enums . ### Expected Behavior after running `bash add_connector.sh <connector-name> <connector-base-url>` code needs to be compiled after template code is created. ### Actual Behavior compilation error before template code is generated because missing connector enums in Routing . ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' run `bash add_connector.sh <connector-name> <connector-base-url>` to create new connector template code .This would throw errors in following files crates/api_models/src/routing.rs:290:30 crates/api_models/src/enums.rs:168:5 ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index e4a317d74f4..2ca33b6910a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2339,6 +2339,7 @@ name = "euclid_wasm" version = "0.1.0" dependencies = [ "api_models", + "common_enums", "currency_conversion", "euclid", "getrandom 0.2.10", @@ -3306,6 +3307,7 @@ name = "kgraph_utils" version = "0.1.0" dependencies = [ "api_models", + "common_enums", "criterion", "euclid", "masking", diff --git a/connector-template/mod.rs b/connector-template/mod.rs index e441b0e5879..e9945a726a9 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -106,6 +106,7 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} { message: response.message, reason: response.reason, attempt_status: None, + connector_transaction_id: None, }) } } @@ -485,7 +486,7 @@ impl api::IncomingWebhook for {{project-name | downcase | pascal_case}} { fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn erased_serde::Serialize>, errors::ConnectorError> { + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(errors::ConnectorError::WebhooksNotImplemented).into_report() } } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index ffefaa2ad2c..535be4dfb15 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -147,104 +147,6 @@ impl Connector { } } -#[derive( - Clone, - Copy, - Debug, - Eq, - Hash, - PartialEq, - serde::Serialize, - serde::Deserialize, - strum::Display, - strum::EnumString, - strum::EnumIter, - strum::EnumVariantNames, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum RoutableConnectors { - #[cfg(feature = "dummy_connector")] - #[serde(rename = "phonypay")] - #[strum(serialize = "phonypay")] - DummyConnector1, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "fauxpay")] - #[strum(serialize = "fauxpay")] - DummyConnector2, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "pretendpay")] - #[strum(serialize = "pretendpay")] - DummyConnector3, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "stripe_test")] - #[strum(serialize = "stripe_test")] - DummyConnector4, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "adyen_test")] - #[strum(serialize = "adyen_test")] - DummyConnector5, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "checkout_test")] - #[strum(serialize = "checkout_test")] - DummyConnector6, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "paypal_test")] - #[strum(serialize = "paypal_test")] - DummyConnector7, - Aci, - Adyen, - Airwallex, - Authorizedotnet, - Bankofamerica, - Bitpay, - Bambora, - Bluesnap, - Boku, - Braintree, - Cashtocode, - Checkout, - Coinbase, - Cryptopay, - Cybersource, - Dlocal, - Fiserv, - Forte, - Globalpay, - Globepay, - Gocardless, - Helcim, - Iatapay, - Klarna, - Mollie, - Multisafepay, - Nexinets, - Nmi, - Noon, - Nuvei, - // Opayo, added as template code for future usage - Opennode, - // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage - Payme, - Paypal, - Payu, - Powertranz, - Prophetpay, - Rapyd, - Shift4, - Square, - Stax, - Stripe, - Trustpay, - // Tsys, - Tsys, - Volt, - Wise, - Worldline, - Worldpay, - Zen, -} - #[cfg(feature = "payouts")] #[derive( Clone, diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 47a44ea7443..2236714da1d 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -4,7 +4,6 @@ use common_utils::errors::ParsingError; use error_stack::IntoReport; use euclid::{ dssa::types::EuclidAnalysable, - enums as euclid_enums, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, @@ -287,71 +286,7 @@ impl From<RoutableConnectorChoice> for RoutableChoiceSerde { impl From<RoutableConnectorChoice> for ast::ConnectorChoice { fn from(value: RoutableConnectorChoice) -> Self { Self { - connector: match value.connector { - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector1 => euclid_enums::Connector::DummyConnector1, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector2 => euclid_enums::Connector::DummyConnector2, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector3 => euclid_enums::Connector::DummyConnector3, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector4 => euclid_enums::Connector::DummyConnector4, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector5 => euclid_enums::Connector::DummyConnector5, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector6 => euclid_enums::Connector::DummyConnector6, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector7 => euclid_enums::Connector::DummyConnector7, - RoutableConnectors::Aci => euclid_enums::Connector::Aci, - RoutableConnectors::Adyen => euclid_enums::Connector::Adyen, - RoutableConnectors::Airwallex => euclid_enums::Connector::Airwallex, - RoutableConnectors::Authorizedotnet => euclid_enums::Connector::Authorizedotnet, - RoutableConnectors::Bambora => euclid_enums::Connector::Bambora, - RoutableConnectors::Bankofamerica => euclid_enums::Connector::Bankofamerica, - RoutableConnectors::Bitpay => euclid_enums::Connector::Bitpay, - RoutableConnectors::Bluesnap => euclid_enums::Connector::Bluesnap, - RoutableConnectors::Boku => euclid_enums::Connector::Boku, - RoutableConnectors::Braintree => euclid_enums::Connector::Braintree, - RoutableConnectors::Cashtocode => euclid_enums::Connector::Cashtocode, - RoutableConnectors::Checkout => euclid_enums::Connector::Checkout, - RoutableConnectors::Coinbase => euclid_enums::Connector::Coinbase, - RoutableConnectors::Cryptopay => euclid_enums::Connector::Cryptopay, - RoutableConnectors::Cybersource => euclid_enums::Connector::Cybersource, - RoutableConnectors::Dlocal => euclid_enums::Connector::Dlocal, - RoutableConnectors::Fiserv => euclid_enums::Connector::Fiserv, - RoutableConnectors::Forte => euclid_enums::Connector::Forte, - RoutableConnectors::Globalpay => euclid_enums::Connector::Globalpay, - RoutableConnectors::Globepay => euclid_enums::Connector::Globepay, - RoutableConnectors::Gocardless => euclid_enums::Connector::Gocardless, - RoutableConnectors::Helcim => euclid_enums::Connector::Helcim, - RoutableConnectors::Iatapay => euclid_enums::Connector::Iatapay, - RoutableConnectors::Klarna => euclid_enums::Connector::Klarna, - RoutableConnectors::Mollie => euclid_enums::Connector::Mollie, - RoutableConnectors::Multisafepay => euclid_enums::Connector::Multisafepay, - RoutableConnectors::Nexinets => euclid_enums::Connector::Nexinets, - RoutableConnectors::Nmi => euclid_enums::Connector::Nmi, - RoutableConnectors::Noon => euclid_enums::Connector::Noon, - RoutableConnectors::Nuvei => euclid_enums::Connector::Nuvei, - RoutableConnectors::Opennode => euclid_enums::Connector::Opennode, - RoutableConnectors::Payme => euclid_enums::Connector::Payme, - RoutableConnectors::Paypal => euclid_enums::Connector::Paypal, - RoutableConnectors::Payu => euclid_enums::Connector::Payu, - RoutableConnectors::Powertranz => euclid_enums::Connector::Powertranz, - RoutableConnectors::Prophetpay => euclid_enums::Connector::Prophetpay, - RoutableConnectors::Rapyd => euclid_enums::Connector::Rapyd, - RoutableConnectors::Shift4 => euclid_enums::Connector::Shift4, - RoutableConnectors::Square => euclid_enums::Connector::Square, - RoutableConnectors::Stax => euclid_enums::Connector::Stax, - RoutableConnectors::Stripe => euclid_enums::Connector::Stripe, - RoutableConnectors::Trustpay => euclid_enums::Connector::Trustpay, - RoutableConnectors::Tsys => euclid_enums::Connector::Tsys, - RoutableConnectors::Volt => euclid_enums::Connector::Volt, - RoutableConnectors::Wise => euclid_enums::Connector::Wise, - RoutableConnectors::Worldline => euclid_enums::Connector::Worldline, - RoutableConnectors::Worldpay => euclid_enums::Connector::Worldpay, - RoutableConnectors::Zen => euclid_enums::Connector::Zen, - }, - + connector: value.connector, #[cfg(not(feature = "connector_choice_mca_id"))] sub_label: value.sub_label, } diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index 88628825ca6..cd061970bff 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -7,6 +7,10 @@ rust-version.workspace = true readme = "README.md" license.workspace = true +[features] +default = ["dummy_connector"] +dummy_connector = [] + [dependencies] diesel = { version = "2.1.0", features = ["postgres"] } serde = { version = "1.0.160", features = ["derive"] } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 063e35933c4..3f343965130 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -59,6 +59,105 @@ pub enum AttemptStatus { DeviceDataCollectionPending, } +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + strum::EnumIter, + strum::EnumVariantNames, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum RoutableConnectors { + #[cfg(feature = "dummy_connector")] + #[serde(rename = "phonypay")] + #[strum(serialize = "phonypay")] + DummyConnector1, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "fauxpay")] + #[strum(serialize = "fauxpay")] + DummyConnector2, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "pretendpay")] + #[strum(serialize = "pretendpay")] + DummyConnector3, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "stripe_test")] + #[strum(serialize = "stripe_test")] + DummyConnector4, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "adyen_test")] + #[strum(serialize = "adyen_test")] + DummyConnector5, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "checkout_test")] + #[strum(serialize = "checkout_test")] + DummyConnector6, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "paypal_test")] + #[strum(serialize = "paypal_test")] + DummyConnector7, + Aci, + Adyen, + Airwallex, + Authorizedotnet, + Bankofamerica, + Bitpay, + Bambora, + Bluesnap, + Boku, + Braintree, + Cashtocode, + Checkout, + Coinbase, + Cryptopay, + Cybersource, + Dlocal, + Fiserv, + Forte, + Globalpay, + Globepay, + Gocardless, + Helcim, + Iatapay, + Klarna, + Mollie, + Multisafepay, + Nexinets, + Nmi, + Noon, + Nuvei, + // Opayo, added as template code for future usage + Opennode, + // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage + Payme, + Paypal, + Payu, + Powertranz, + Prophetpay, + Rapyd, + Shift4, + Square, + Stax, + Stripe, + Trustpay, + // Tsys, + Tsys, + Volt, + Wise, + Worldline, + Worldpay, + Zen, +} + impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs index dc6d9f66a58..68e081c7aa9 100644 --- a/crates/euclid/src/enums.rs +++ b/crates/euclid/src/enums.rs @@ -1,8 +1,7 @@ pub use common_enums::{ AuthenticationType, CaptureMethod, CardNetwork, Country, Currency, - FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, + FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, RoutableConnectors, }; -use serde::{Deserialize, Serialize}; use strum::VariantNames; pub trait CollectVariants { @@ -24,6 +23,7 @@ macro_rules! collect_variants { pub(crate) use collect_variants; collect_variants!(PaymentMethod); +collect_variants!(RoutableConnectors); collect_variants!(PaymentType); collect_variants!(MandateType); collect_variants!(MandateAcceptanceType); @@ -33,105 +33,8 @@ collect_variants!(AuthenticationType); collect_variants!(CaptureMethod); collect_variants!(Currency); collect_variants!(Country); -collect_variants!(Connector); collect_variants!(SetupFutureUsage); -#[derive( - Debug, - Copy, - Clone, - PartialEq, - Eq, - Hash, - Serialize, - Deserialize, - strum::Display, - strum::EnumVariantNames, - strum::EnumIter, - strum::EnumString, - frunk::LabelledGeneric, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum Connector { - #[cfg(feature = "dummy_connector")] - #[serde(rename = "phonypay")] - #[strum(serialize = "phonypay")] - DummyConnector1, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "fauxpay")] - #[strum(serialize = "fauxpay")] - DummyConnector2, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "pretendpay")] - #[strum(serialize = "pretendpay")] - DummyConnector3, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "stripe_test")] - #[strum(serialize = "stripe_test")] - DummyConnector4, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "adyen_test")] - #[strum(serialize = "adyen_test")] - DummyConnector5, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "checkout_test")] - #[strum(serialize = "checkout_test")] - DummyConnector6, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "paypal_test")] - #[strum(serialize = "paypal_test")] - DummyConnector7, - Aci, - Adyen, - Airwallex, - Authorizedotnet, - Bambora, - Bankofamerica, - Bitpay, - Bluesnap, - Boku, - Braintree, - Cashtocode, - Checkout, - Coinbase, - Cryptopay, - Cybersource, - Dlocal, - Fiserv, - Forte, - Globalpay, - Globepay, - Gocardless, - Helcim, - Iatapay, - Klarna, - Mollie, - Multisafepay, - Nexinets, - Nmi, - Noon, - Nuvei, - Opennode, - Payme, - Paypal, - Payu, - Powertranz, - Prophetpay, - Rapyd, - Shift4, - Square, - Stax, - Stripe, - Trustpay, - Tsys, - Volt, - Wise, - Worldline, - Worldpay, - Zen, -} - #[derive( Clone, Debug, diff --git a/crates/euclid/src/frontend/ast.rs b/crates/euclid/src/frontend/ast.rs index 3adb06ab187..0dad9b53c32 100644 --- a/crates/euclid/src/frontend/ast.rs +++ b/crates/euclid/src/frontend/ast.rs @@ -2,16 +2,14 @@ pub mod lowering; #[cfg(feature = "ast_parser")] pub mod parser; +use common_enums::RoutableConnectors; use serde::{Deserialize, Serialize}; -use crate::{ - enums::Connector, - types::{DataType, Metadata}, -}; +use crate::types::{DataType, Metadata}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct ConnectorChoice { - pub connector: Connector, + pub connector: RoutableConnectors, #[cfg(not(feature = "connector_choice_mca_id"))] pub sub_label: Option<String>, } diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs index 7f2fc252d23..f8cef1f9295 100644 --- a/crates/euclid/src/frontend/dir.rs +++ b/crates/euclid/src/frontend/dir.rs @@ -13,7 +13,7 @@ macro_rules! dirval { (Connector = $name:ident) => { $crate::frontend::dir::DirValue::Connector(Box::new( $crate::frontend::ast::ConnectorChoice { - connector: $crate::frontend::dir::enums::Connector::$name, + connector: $crate::enums::RoutableConnectors::$name, }, )) }; @@ -51,7 +51,7 @@ macro_rules! dirval { (Connector = $name:ident) => { $crate::frontend::dir::DirValue::Connector(Box::new( $crate::frontend::ast::ConnectorChoice { - connector: $crate::frontend::dir::enums::Connector::$name, + connector: $crate::enums::RoutableConnectors::$name, sub_label: None, }, )) @@ -60,7 +60,7 @@ macro_rules! dirval { (Connector = ($name:ident, $sub_label:literal)) => { $crate::frontend::dir::DirValue::Connector(Box::new( $crate::frontend::ast::ConnectorChoice { - connector: $crate::frontend::dir::enums::Connector::$name, + connector: $crate::enums::RoutableConnectors::$name, sub_label: Some($sub_label.to_string()), }, )) @@ -464,7 +464,7 @@ impl DirKeyKind { .collect(), ), Self::Connector => Some( - enums::Connector::iter() + common_enums::RoutableConnectors::iter() .map(|connector| { DirValue::Connector(Box::new(ast::ConnectorChoice { connector, diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index f049ad35328..0b71f916d03 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -2,9 +2,9 @@ use strum::VariantNames; use crate::enums::collect_variants; pub use crate::enums::{ - AuthenticationType, CaptureMethod, CardNetwork, Connector, Country, Country as BusinessCountry, + AuthenticationType, CaptureMethod, CardNetwork, Country, Country as BusinessCountry, Country as BillingCountry, Currency as PaymentCurrency, MandateAcceptanceType, MandateType, - PaymentMethod, PaymentType, SetupFutureUsage, + PaymentMethod, PaymentType, RoutableConnectors, SetupFutureUsage, }; #[derive( diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index 47e349847ef..8c96a7f67da 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -20,6 +20,7 @@ api_models = { version = "0.1.0", path = "../api_models", package = "api_models" currency_conversion = { version = "0.1.0", path = "../currency_conversion" } euclid = { path = "../euclid", features = [] } kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" } +common_enums = { version = "0.1.0", path = "../common_enums" } # Third party crates getrandom = { version = "0.2.10", features = ["js"] } diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index 48d9ac0d82a..cab82f8ce41 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -7,6 +7,7 @@ use std::{ }; use api_models::{admin as admin_api, routing::ConnectorSelection}; +use common_enums::RoutableConnectors; use currency_conversion::{ conversion::convert as convert_currency, types as currency_conversion_types, }; @@ -17,7 +18,6 @@ use euclid::{ graph::{self, Memoization}, state_machine, truth, }, - enums, frontend::{ ast, dir::{self, enums as dir_enums}, @@ -61,8 +61,8 @@ pub fn convert_forex_value(amount: i64, from_currency: JsValue, to_currency: JsV .get() .ok_or("Forex Data not seeded") .err_to_js()?; - let from_currency: enums::Currency = serde_wasm_bindgen::from_value(from_currency)?; - let to_currency: enums::Currency = serde_wasm_bindgen::from_value(to_currency)?; + let from_currency: common_enums::Currency = serde_wasm_bindgen::from_value(from_currency)?; + let to_currency: common_enums::Currency = serde_wasm_bindgen::from_value(to_currency)?; let converted_amount = convert_currency(forex_data, from_currency, to_currency, amount) .map_err(|_| "conversion not possible for provided values") .err_to_js()?; @@ -80,7 +80,7 @@ pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult { .iter() .map(|mca| { Ok::<_, strum::ParseError>(ast::ConnectorChoice { - connector: dir_enums::Connector::from_str(&mca.connector_name)?, + connector: RoutableConnectors::from_str(&mca.connector_name)?, #[cfg(not(feature = "connector_choice_mca_id"))] sub_label: mca.business_sub_label.clone(), }) @@ -183,7 +183,9 @@ pub fn run_program(program: JsValue, input: JsValue) -> JsResult { #[wasm_bindgen(js_name = getAllConnectors)] pub fn get_all_connectors() -> JsResult { - Ok(serde_wasm_bindgen::to_value(enums::Connector::VARIANTS)?) + Ok(serde_wasm_bindgen::to_value( + common_enums::RoutableConnectors::VARIANTS, + )?) } #[wasm_bindgen(js_name = getAllKeys)] diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index cd0adf0bc8a..44a73dae4d7 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -11,6 +11,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } +common_enums = { version = "0.1.0", path = "../common_enums" } euclid = { version = "0.1.0", path = "../euclid" } masking = { version = "0.1.0", path = "../masking/" } diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index deea51bd880..0e224a8f3d9 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -5,10 +5,7 @@ use api_models::{ }; use euclid::{ dssa::graph::{self, DomainIdentifier}, - frontend::{ - ast, - dir::{self, enums as dir_enums}, - }, + frontend::{ast, dir}, types::{NumValue, NumValueRefinement}, }; @@ -277,7 +274,7 @@ fn compile_merchant_connector_graph( builder: &mut graph::KnowledgeGraphBuilder<'_>, mca: admin_api::MerchantConnectorResponse, ) -> Result<(), KgraphError> { - let connector = dir_enums::Connector::from_str(&mca.connector_name) + let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name) .map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?; let mut agg_nodes: Vec<(graph::NodeId, graph::Relation)> = Vec::new(); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1c40ef81f49..d308c98b75d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -81,7 +81,7 @@ pub async fn payments_operation_core<F, Req, Op, FData, Ctx>( req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, - eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>, + eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>, header_payload: HeaderPayload, ) -> RouterResult<( PaymentData<F>, diff --git a/crates/router/src/core/payments/routing/transformers.rs b/crates/router/src/core/payments/routing/transformers.rs index 5704f82f498..b273f18f3fd 100644 --- a/crates/router/src/core/payments/routing/transformers.rs +++ b/crates/router/src/core/payments/routing/transformers.rs @@ -1,15 +1,15 @@ -use api_models::{self, enums as api_enums, routing as routing_types}; +use api_models::{self, routing as routing_types}; use diesel_models::enums as storage_enums; use euclid::{enums as dsl_enums, frontend::ast as dsl_ast}; -use crate::types::transformers::{ForeignFrom, ForeignInto}; +use crate::types::transformers::ForeignFrom; impl ForeignFrom<routing_types::RoutableConnectorChoice> for dsl_ast::ConnectorChoice { fn foreign_from(from: routing_types::RoutableConnectorChoice) -> Self { Self { // #[cfg(feature = "backwards_compatibility")] // choice_kind: from.choice_kind.foreign_into(), - connector: from.connector.foreign_into(), + connector: from.connector, #[cfg(not(feature = "connector_choice_mca_id"))] sub_label: from.sub_label, } @@ -52,72 +52,3 @@ impl ForeignFrom<storage_enums::MandateDataType> for dsl_enums::MandateType { } } } - -impl ForeignFrom<api_enums::RoutableConnectors> for dsl_enums::Connector { - fn foreign_from(from: api_enums::RoutableConnectors) -> Self { - match from { - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector1 => Self::DummyConnector1, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector2 => Self::DummyConnector2, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector3 => Self::DummyConnector3, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector4 => Self::DummyConnector4, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector5 => Self::DummyConnector5, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector6 => Self::DummyConnector6, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector7 => Self::DummyConnector7, - api_enums::RoutableConnectors::Aci => Self::Aci, - api_enums::RoutableConnectors::Adyen => Self::Adyen, - api_enums::RoutableConnectors::Airwallex => Self::Airwallex, - api_enums::RoutableConnectors::Authorizedotnet => Self::Authorizedotnet, - api_enums::RoutableConnectors::Bambora => Self::Bambora, - api_enums::RoutableConnectors::Bankofamerica => Self::Bankofamerica, - api_enums::RoutableConnectors::Bitpay => Self::Bitpay, - api_enums::RoutableConnectors::Bluesnap => Self::Bluesnap, - api_enums::RoutableConnectors::Boku => Self::Boku, - api_enums::RoutableConnectors::Braintree => Self::Braintree, - api_enums::RoutableConnectors::Cashtocode => Self::Cashtocode, - api_enums::RoutableConnectors::Checkout => Self::Checkout, - api_enums::RoutableConnectors::Coinbase => Self::Coinbase, - api_enums::RoutableConnectors::Cryptopay => Self::Cryptopay, - api_enums::RoutableConnectors::Cybersource => Self::Cybersource, - api_enums::RoutableConnectors::Dlocal => Self::Dlocal, - api_enums::RoutableConnectors::Fiserv => Self::Fiserv, - api_enums::RoutableConnectors::Forte => Self::Forte, - api_enums::RoutableConnectors::Globalpay => Self::Globalpay, - api_enums::RoutableConnectors::Globepay => Self::Globepay, - api_enums::RoutableConnectors::Gocardless => Self::Gocardless, - api_enums::RoutableConnectors::Helcim => Self::Helcim, - api_enums::RoutableConnectors::Iatapay => Self::Iatapay, - api_enums::RoutableConnectors::Klarna => Self::Klarna, - api_enums::RoutableConnectors::Mollie => Self::Mollie, - api_enums::RoutableConnectors::Multisafepay => Self::Multisafepay, - api_enums::RoutableConnectors::Nexinets => Self::Nexinets, - api_enums::RoutableConnectors::Nmi => Self::Nmi, - api_enums::RoutableConnectors::Noon => Self::Noon, - api_enums::RoutableConnectors::Nuvei => Self::Nuvei, - api_enums::RoutableConnectors::Opennode => Self::Opennode, - api_enums::RoutableConnectors::Payme => Self::Payme, - api_enums::RoutableConnectors::Paypal => Self::Paypal, - api_enums::RoutableConnectors::Payu => Self::Payu, - api_enums::RoutableConnectors::Powertranz => Self::Powertranz, - api_enums::RoutableConnectors::Prophetpay => Self::Prophetpay, - api_enums::RoutableConnectors::Rapyd => Self::Rapyd, - api_enums::RoutableConnectors::Shift4 => Self::Shift4, - api_enums::RoutableConnectors::Square => Self::Square, - api_enums::RoutableConnectors::Stax => Self::Stax, - api_enums::RoutableConnectors::Stripe => Self::Stripe, - api_enums::RoutableConnectors::Trustpay => Self::Trustpay, - api_enums::RoutableConnectors::Tsys => Self::Tsys, - api_enums::RoutableConnectors::Volt => Self::Volt, - api_enums::RoutableConnectors::Wise => Self::Wise, - api_enums::RoutableConnectors::Worldline => Self::Worldline, - api_enums::RoutableConnectors::Worldpay => Self::Worldpay, - api_enums::RoutableConnectors::Zen => Self::Zen, - } - } -} diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 45aad93371e..66a8ba7936d 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -9,7 +9,6 @@ use common_utils::{ }; use diesel_models::enums as storage_enums; use error_stack::{IntoReport, ResultExt}; -use euclid::enums as dsl_enums; use masking::{ExposeInterface, PeekInterface}; use super::domain; @@ -174,25 +173,11 @@ impl ForeignFrom<storage_enums::MandateDataType> for api_models::payments::Manda } } -impl ForeignTryFrom<api_enums::Connector> for api_enums::RoutableConnectors { +impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { type Error = error_stack::Report<common_utils::errors::ValidationError>; fn foreign_try_from(from: api_enums::Connector) -> Result<Self, Self::Error> { Ok(match from { - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector1 => Self::DummyConnector1, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector2 => Self::DummyConnector2, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector3 => Self::DummyConnector3, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector4 => Self::DummyConnector4, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector5 => Self::DummyConnector5, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector6 => Self::DummyConnector6, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector7 => Self::DummyConnector7, api_enums::Connector::Aci => Self::Aci, api_enums::Connector::Adyen => Self::Adyen, api_enums::Connector::Airwallex => Self::Airwallex, @@ -253,76 +238,21 @@ impl ForeignTryFrom<api_enums::Connector> for api_enums::RoutableConnectors { api_enums::Connector::Worldline => Self::Worldline, api_enums::Connector::Worldpay => Self::Worldpay, api_enums::Connector::Zen => Self::Zen, - }) - } -} - -impl ForeignFrom<dsl_enums::Connector> for api_enums::RoutableConnectors { - fn foreign_from(from: dsl_enums::Connector) -> Self { - match from { #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector1 => Self::DummyConnector1, + api_enums::Connector::DummyConnector1 => Self::DummyConnector1, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector2 => Self::DummyConnector2, + api_enums::Connector::DummyConnector2 => Self::DummyConnector2, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector3 => Self::DummyConnector3, + api_enums::Connector::DummyConnector3 => Self::DummyConnector3, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector4 => Self::DummyConnector4, + api_enums::Connector::DummyConnector4 => Self::DummyConnector4, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector5 => Self::DummyConnector5, + api_enums::Connector::DummyConnector5 => Self::DummyConnector5, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector6 => Self::DummyConnector6, + api_enums::Connector::DummyConnector6 => Self::DummyConnector6, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector7 => Self::DummyConnector7, - dsl_enums::Connector::Aci => Self::Aci, - dsl_enums::Connector::Adyen => Self::Adyen, - dsl_enums::Connector::Airwallex => Self::Airwallex, - dsl_enums::Connector::Authorizedotnet => Self::Authorizedotnet, - dsl_enums::Connector::Bambora => Self::Bambora, - dsl_enums::Connector::Bankofamerica => Self::Bankofamerica, - dsl_enums::Connector::Bitpay => Self::Bitpay, - dsl_enums::Connector::Bluesnap => Self::Bluesnap, - dsl_enums::Connector::Boku => Self::Boku, - dsl_enums::Connector::Braintree => Self::Braintree, - dsl_enums::Connector::Cashtocode => Self::Cashtocode, - dsl_enums::Connector::Checkout => Self::Checkout, - dsl_enums::Connector::Coinbase => Self::Coinbase, - dsl_enums::Connector::Cryptopay => Self::Cryptopay, - dsl_enums::Connector::Cybersource => Self::Cybersource, - dsl_enums::Connector::Dlocal => Self::Dlocal, - dsl_enums::Connector::Fiserv => Self::Fiserv, - dsl_enums::Connector::Forte => Self::Forte, - dsl_enums::Connector::Globalpay => Self::Globalpay, - dsl_enums::Connector::Globepay => Self::Globepay, - dsl_enums::Connector::Gocardless => Self::Gocardless, - dsl_enums::Connector::Helcim => Self::Helcim, - dsl_enums::Connector::Iatapay => Self::Iatapay, - dsl_enums::Connector::Klarna => Self::Klarna, - dsl_enums::Connector::Mollie => Self::Mollie, - dsl_enums::Connector::Multisafepay => Self::Multisafepay, - dsl_enums::Connector::Nexinets => Self::Nexinets, - dsl_enums::Connector::Nmi => Self::Nmi, - dsl_enums::Connector::Noon => Self::Noon, - dsl_enums::Connector::Nuvei => Self::Nuvei, - dsl_enums::Connector::Opennode => Self::Opennode, - dsl_enums::Connector::Payme => Self::Payme, - dsl_enums::Connector::Paypal => Self::Paypal, - dsl_enums::Connector::Payu => Self::Payu, - dsl_enums::Connector::Powertranz => Self::Powertranz, - dsl_enums::Connector::Prophetpay => Self::Prophetpay, - dsl_enums::Connector::Rapyd => Self::Rapyd, - dsl_enums::Connector::Shift4 => Self::Shift4, - dsl_enums::Connector::Square => Self::Square, - dsl_enums::Connector::Stax => Self::Stax, - dsl_enums::Connector::Stripe => Self::Stripe, - dsl_enums::Connector::Trustpay => Self::Trustpay, - dsl_enums::Connector::Tsys => Self::Tsys, - dsl_enums::Connector::Volt => Self::Volt, - dsl_enums::Connector::Wise => Self::Wise, - dsl_enums::Connector::Worldline => Self::Worldline, - dsl_enums::Connector::Worldpay => Self::Worldpay, - dsl_enums::Connector::Zen => Self::Zen, - } + api_enums::Connector::DummyConnector7 => Self::DummyConnector7, + }) } } diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 9a30fe9d757..7ed5e65151e 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -45,7 +45,7 @@ cd $SCRIPT/.. # Remove template files if already created for this connector rm -rf $conn/$payment_gateway $conn/$payment_gateway.rs -git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml crates/api_models/src/enums.rs crates/euclid/src/enums.rs crates/api_models/src/routing.rs $src/core/payments/flows.rs $src/core/admin.rs $src/core/payments/routing/transformers.rs $src/types/transformers.rs +git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml crates/api_models/src/enums.rs crates/euclid/src/enums.rs crates/api_models/src/routing.rs $src/core/payments/flows.rs crates/common_enums/src/enums.rs $src/types/transformers.rs $src/core/admin.rs # Add enum for this connector in required places previous_connector='' @@ -61,14 +61,12 @@ sed -r -i'' -e "s/\"$previous_connector\",/\"$previous_connector\",\n \"${pa sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/api_models/src/enums.rs sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/euclid/src/enums.rs sed -i '' -e "s/\(match connector_name {\)/\1\n\t\tapi_enums::Connector::${payment_gateway_camelcase} => {${payment_gateway}::transformers::${payment_gateway_camelcase}AuthType::try_from(val)?;Ok(())}/" $src/core/admin.rs -sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tapi_enums::RoutableConnectors::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/core/payments/routing/transformers.rs -sed -i'' -e "s|dsl_enums::Connector::$previous_connector_camelcase \(.*\)|dsl_enums::Connector::$previous_connector_camelcase \1\n\t\t\tdsl_enums::Connector::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/types/transformers.rs -sed -i'' -e "s|api_enums::Connector::$previous_connector_camelcase \(.*\)|api_enums::Connector::$previous_connector_camelcase \1\n\t\t\tapi_enums::Connector::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/types/transformers.rs -sed -i'' -e "s/\(pub enum RoutableConnectors {\)/\1\n\t${payment_gateway_camelcase},/" crates/api_models/src/enums.rs +sed -i'' -e "s/\(pub enum RoutableConnectors {\)/\1\n\t${payment_gateway_camelcase},/" crates/common_enums/src/enums.rs +sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tapi_enums::Connector::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/types/transformers.rs sed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnector::${payment_gateway_camelcase},/" $src/core/payments/flows.rs # Remove temporary files created in above step -rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e $src/core/admin.rs-e $src/core/payments/routing/transformers.rs-e $src/types/transformers.rs-e +rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e crates/common_enums/src/enums.rs-e $src/types/transformers.rs-e $src/core/admin.rs-e cd $conn/ # Generate template files for the connector
2023-11-28T10:06:59Z
## 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 have 2 changes 1)Transferring routable connectors to shared enums will reduce the redundancy associated with employing Euclid enums. 2)fixing connector code template script ### 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 PR have 2 changes 1)Transferring routable connectors to shared enums will reduce the redundancy associated with employing Euclid enums. 2)fixing connector code template script ## 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)? --> By running `cargo clippy --all-features --all-targets` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c0116db271f6afc1b93c04705209bfc346228c68
juspay/hyperswitch
juspay__hyperswitch-2930
Bug: [FEATURE]: Add partner flow for PayPal ### Feature Description PayPal offers an onboarding flow, where merchants can be onboarded directly from a partner account. But for that, we need to change the authentication logic for PayPal request. We should be able to take a 3rd field in the connector_account_details. So we need to support SignatureKey as well. ### Possible Implementation Add support for SignatureKey ### 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/paypal.rs b/crates/router/src/connector/paypal.rs index e514ebbed2f..0e8cff8c056 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -5,10 +5,10 @@ use base64::Engine; use common_utils::ext_traits::ByteSliceExt; use diesel_models::enums; use error_stack::{IntoReport, ResultExt}; -use masking::PeekInterface; +use masking::{ExposeInterface, PeekInterface, Secret}; use transformers as paypal; -use self::transformers::{PaypalAuthResponse, PaypalMeta, PaypalWebhookEventType}; +use self::transformers::{auth_headers, PaypalAuthResponse, PaypalMeta, PaypalWebhookEventType}; use super::utils::PaymentsCompleteAuthorizeRequestData; use crate::{ configs::settings, @@ -31,7 +31,7 @@ use crate::{ self, api::{self, CompleteAuthorize, ConnectorCommon, ConnectorCommonExt, VerifyWebhookSource}, transformers::ForeignFrom, - ErrorResponse, Response, + ConnectorAuthType, ErrorResponse, Response, }, utils::{self, BytesExt}, }; @@ -110,8 +110,8 @@ where .clone() .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; let key = &req.attempt_id; - - Ok(vec![ + let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?; + let mut headers = vec![ ( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), @@ -121,17 +121,57 @@ where format!("Bearer {}", access_token.token.peek()).into_masked(), ), ( - "Prefer".to_string(), + auth_headers::PREFER.to_string(), "return=representation".to_string().into(), ), ( - "PayPal-Request-Id".to_string(), + auth_headers::PAYPAL_REQUEST_ID.to_string(), key.to_string().into_masked(), ), - ]) + ]; + if let Ok(paypal::PaypalConnectorCredentials::PartnerIntegration(credentials)) = + auth.get_credentials() + { + let auth_assertion_header = + construct_auth_assertion_header(&credentials.payer_id, &credentials.client_id); + headers.extend(vec![ + ( + auth_headers::PAYPAL_AUTH_ASSERTION.to_string(), + auth_assertion_header.to_string().into_masked(), + ), + ( + auth_headers::PAYPAL_PARTNER_ATTRIBUTION_ID.to_string(), + "HyperSwitchPPCP_SP".to_string().into(), + ), + ]) + } else { + headers.extend(vec![( + auth_headers::PAYPAL_PARTNER_ATTRIBUTION_ID.to_string(), + "HyperSwitchlegacy_Ecom".to_string().into(), + )]) + } + Ok(headers) } } +fn construct_auth_assertion_header( + payer_id: &Secret<String>, + client_id: &Secret<String>, +) -> String { + let algorithm = consts::BASE64_ENGINE + .encode("{\"alg\":\"none\"}") + .to_string(); + let merchant_credentials = format!( + "{{\"iss\":\"{}\",\"payer_id\":\"{}\"}}", + client_id.clone().expose(), + payer_id.clone().expose() + ); + let encoded_credentials = consts::BASE64_ENGINE + .encode(merchant_credentials) + .to_string(); + format!("{algorithm}.{encoded_credentials}.") +} + impl ConnectorCommon for Paypal { fn id(&self) -> &'static str { "paypal" @@ -151,14 +191,14 @@ impl ConnectorCommon for Paypal { fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, + auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth: paypal::PaypalAuthType = auth_type - .try_into() - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let auth = paypal::PaypalAuthType::try_from(auth_type)?; + let credentials = auth.get_credentials()?; + Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.into_masked(), + credentials.get_client_secret().into_masked(), )]) } @@ -260,15 +300,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t req: &types::RefreshTokenRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth: paypal::PaypalAuthType = (&req.connector_auth_type) - .try_into() - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - - let auth_id = auth - .key1 - .zip(auth.api_key) - .map(|(key1, api_key)| format!("{}:{}", key1, api_key)); - let auth_val = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id.peek())); + let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?; + let credentials = auth.get_credentials()?; + let auth_val = credentials.generate_authorization_value(); Ok(vec![ ( @@ -998,15 +1032,9 @@ impl >, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth: paypal::PaypalAuthType = (&req.connector_auth_type) - .try_into() - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - - let auth_id = auth - .key1 - .zip(auth.api_key) - .map(|(key1, api_key)| format!("{}:{}", key1, api_key)); - let auth_val = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id.peek())); + let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?; + let credentials = auth.get_credentials()?; + let auth_val = credentials.generate_authorization_value(); Ok(vec![ ( diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 5468c6bb806..d023077ff00 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -1,7 +1,8 @@ use api_models::{enums, payments::BankRedirectData}; +use base64::Engine; use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; @@ -11,10 +12,11 @@ use crate::{ self, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData, BankRedirectBillingData, CardData, PaymentsAuthorizeRequestData, }, + consts, core::errors, services, types::{ - self, api, storage::enums as storage_enums, transformers::ForeignFrom, + self, api, storage::enums as storage_enums, transformers::ForeignFrom, ConnectorAuthType, VerifyWebhookSourceResponseData, }, }; @@ -57,6 +59,12 @@ mod webhook_headers { pub const PAYPAL_CERT_URL: &str = "paypal-cert-url"; pub const PAYPAL_AUTH_ALGO: &str = "paypal-auth-algo"; } +pub mod auth_headers { + pub const PAYPAL_PARTNER_ATTRIBUTION_ID: &str = "PayPal-Partner-Attribution-Id"; + pub const PREFER: &str = "Prefer"; + pub const PAYPAL_REQUEST_ID: &str = "PayPal-Request-Id"; + pub const PAYPAL_AUTH_ASSERTION: &str = "PayPal-Auth-Assertion"; +} #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "UPPERCASE")] @@ -72,19 +80,111 @@ pub struct OrderAmount { pub value: String, } +#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)] +pub struct OrderRequestAmount { + pub currency_code: storage_enums::Currency, + pub value: String, + pub breakdown: AmountBreakdown, +} + +impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for OrderRequestAmount { + fn from(item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>) -> Self { + Self { + currency_code: item.router_data.request.currency, + value: item.amount.to_owned(), + breakdown: AmountBreakdown { + item_total: OrderAmount { + currency_code: item.router_data.request.currency, + value: item.amount.to_owned(), + }, + }, + } + } +} + +#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)] +pub struct AmountBreakdown { + item_total: OrderAmount, +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct PurchaseUnitRequest { reference_id: Option<String>, //reference for an item in purchase_units invoice_id: Option<String>, //The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. custom_id: Option<String>, //Used to reconcile client transactions with PayPal transactions. - amount: OrderAmount, + amount: OrderRequestAmount, + #[serde(skip_serializing_if = "Option::is_none")] + payee: Option<Payee>, + shipping: Option<ShippingAddress>, + items: Vec<ItemDetails>, } -#[derive(Debug, Serialize)] +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct Payee { + merchant_id: Secret<String>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct ItemDetails { + name: String, + quantity: u16, + unit_amount: OrderAmount, +} + +impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ItemDetails { + fn from(item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>) -> Self { + Self { + name: format!( + "Payment for invoice {}", + item.router_data.connector_request_reference_id + ), + quantity: 1, + unit_amount: OrderAmount { + currency_code: item.router_data.request.currency, + value: item.amount.to_string(), + }, + } + } +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct Address { address_line_1: Option<Secret<String>>, postal_code: Option<Secret<String>>, country_code: api_models::enums::CountryAlpha2, + admin_area_2: Option<String>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct ShippingAddress { + address: Option<Address>, + name: Option<ShippingName>, +} + +impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ShippingAddress { + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + address: get_address_info(item.router_data.address.shipping.as_ref())?, + name: Some(ShippingName { + full_name: item + .router_data + .address + .shipping + .as_ref() + .and_then(|inner_data| inner_data.address.as_ref()) + .and_then(|inner_data| inner_data.first_name.clone()), + }), + }) + } +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct ShippingName { + full_name: Option<Secret<String>>, } #[derive(Debug, Serialize)] @@ -124,6 +224,22 @@ pub struct RedirectRequest { pub struct ContextStruct { return_url: Option<String>, cancel_url: Option<String>, + user_action: Option<UserAction>, + shipping_preference: ShippingPreference, +} + +#[derive(Debug, Serialize)] +pub enum UserAction { + #[serde(rename = "PAY_NOW")] + PayNow, +} + +#[derive(Debug, Serialize)] +pub enum ShippingPreference { + #[serde(rename = "SET_PROVIDED_ADDRESS")] + SetProvidedAddress, + #[serde(rename = "GET_FROM_FILE")] + GetFromFile, } #[derive(Debug, Serialize)] @@ -158,6 +274,7 @@ fn get_address_info( country_code: address.get_country()?.to_owned(), address_line_1: address.line1.clone(), postal_code: address.zip.clone(), + admin_area_2: address.city.clone(), }), None => None, }; @@ -180,6 +297,12 @@ fn get_payment_source( experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), + shipping_preference: if item.address.shipping.is_some() { + ShippingPreference::SetProvidedAddress + } else { + ShippingPreference::GetFromFile + }, + user_action: Some(UserAction::PayNow), }, })), BankRedirectData::Giropay { @@ -194,6 +317,12 @@ fn get_payment_source( experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), + shipping_preference: if item.address.shipping.is_some() { + ShippingPreference::SetProvidedAddress + } else { + ShippingPreference::GetFromFile + }, + user_action: Some(UserAction::PayNow), }, })), BankRedirectData::Ideal { @@ -208,6 +337,12 @@ fn get_payment_source( experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), + shipping_preference: if item.address.shipping.is_some() { + ShippingPreference::SetProvidedAddress + } else { + ShippingPreference::GetFromFile + }, + user_action: Some(UserAction::PayNow), }, })), BankRedirectData::Sofort { @@ -220,6 +355,12 @@ fn get_payment_source( experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), + shipping_preference: if item.address.shipping.is_some() { + ShippingPreference::SetProvidedAddress + } else { + ShippingPreference::GetFromFile + }, + user_action: Some(UserAction::PayNow), }, })), BankRedirectData::BancontactCard { .. } @@ -247,11 +388,24 @@ fn get_payment_source( } } +fn get_payee(auth_type: &PaypalAuthType) -> Option<Payee> { + auth_type + .get_credentials() + .ok() + .and_then(|credentials| credentials.get_payer_id()) + .map(|payer_id| Payee { + merchant_id: payer_id, + }) +} + impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { + let paypal_auth: PaypalAuthType = + PaypalAuthType::try_from(&item.router_data.connector_auth_type)?; + let payee = get_payee(&paypal_auth); match item.router_data.request.payment_method_data { api_models::payments::PaymentMethodData::Card(ref ccard) => { let intent = if item.router_data.request.is_auto_capture()? { @@ -259,18 +413,20 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP } else { PaypalPaymentIntent::Authorize }; - let amount = OrderAmount { - currency_code: item.router_data.request.currency, - value: item.amount.to_owned(), - }; + let amount = OrderRequestAmount::from(item); let connector_request_reference_id = item.router_data.connector_request_reference_id.clone(); + let shipping_address = ShippingAddress::try_from(item)?; + let item_details = vec![ItemDetails::from(item)]; let purchase_units = vec![PurchaseUnitRequest { reference_id: Some(connector_request_reference_id.clone()), custom_id: Some(connector_request_reference_id.clone()), invoice_id: Some(connector_request_reference_id), amount, + payee, + shipping: Some(shipping_address), + items: item_details, }]; let card = item.router_data.request.get_card()?; let expiry = Some(card.get_expiry_date_as_yyyymm("-")); @@ -306,25 +462,29 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP } else { PaypalPaymentIntent::Authorize }; - let amount = OrderAmount { - currency_code: item.router_data.request.currency, - value: item.amount.to_owned(), - }; + let amount = OrderRequestAmount::from(item); let connector_req_reference_id = item.router_data.connector_request_reference_id.clone(); + let shipping_address = ShippingAddress::try_from(item)?; + let item_details = vec![ItemDetails::from(item)]; let purchase_units = vec![PurchaseUnitRequest { reference_id: Some(connector_req_reference_id.clone()), custom_id: Some(connector_req_reference_id.clone()), invoice_id: Some(connector_req_reference_id), amount, + payee, + shipping: Some(shipping_address), + items: item_details, }]; let payment_source = Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest { experience_context: ContextStruct { return_url: item.router_data.request.complete_authorize_url.clone(), cancel_url: item.router_data.request.complete_authorize_url.clone(), + shipping_preference: ShippingPreference::SetProvidedAddress, + user_action: Some(UserAction::PayNow), }, })); @@ -374,18 +534,20 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP connector: "Paypal".to_string(), })? }; - let amount = OrderAmount { - currency_code: item.router_data.request.currency, - value: item.amount.to_owned(), - }; + let amount = OrderRequestAmount::from(item); let connector_req_reference_id = item.router_data.connector_request_reference_id.clone(); + let shipping_address = ShippingAddress::try_from(item)?; + let item_details = vec![ItemDetails::from(item)]; let purchase_units = vec![PurchaseUnitRequest { reference_id: Some(connector_req_reference_id.clone()), custom_id: Some(connector_req_reference_id.clone()), invoice_id: Some(connector_req_reference_id), amount, + payee, + shipping: Some(shipping_address), + items: item_details, }]; let payment_source = Some(get_payment_source(item.router_data, bank_redirection_data)?); @@ -604,19 +766,98 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaypalAuthUpdateResponse, T, typ } #[derive(Debug)] -pub struct PaypalAuthType { - pub(super) api_key: Secret<String>, - pub(super) key1: Secret<String>, +pub enum PaypalAuthType { + TemporaryAuth, + AuthWithDetails(PaypalConnectorCredentials), +} + +#[derive(Debug)] +pub enum PaypalConnectorCredentials { + StandardIntegration(StandardFlowCredentials), + PartnerIntegration(PartnerFlowCredentials), } -impl TryFrom<&types::ConnectorAuthType> for PaypalAuthType { +impl PaypalConnectorCredentials { + pub fn get_client_id(&self) -> Secret<String> { + match self { + Self::StandardIntegration(item) => item.client_id.clone(), + Self::PartnerIntegration(item) => item.client_id.clone(), + } + } + + pub fn get_client_secret(&self) -> Secret<String> { + match self { + Self::StandardIntegration(item) => item.client_secret.clone(), + Self::PartnerIntegration(item) => item.client_secret.clone(), + } + } + + pub fn get_payer_id(&self) -> Option<Secret<String>> { + match self { + Self::StandardIntegration(_) => None, + Self::PartnerIntegration(item) => Some(item.payer_id.clone()), + } + } + + pub fn generate_authorization_value(&self) -> String { + let auth_id = format!( + "{}:{}", + self.get_client_id().expose(), + self.get_client_secret().expose(), + ); + format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id)) + } +} + +#[derive(Debug)] +pub struct StandardFlowCredentials { + pub(super) client_id: Secret<String>, + pub(super) client_secret: Secret<String>, +} + +#[derive(Debug)] +pub struct PartnerFlowCredentials { + pub(super) client_id: Secret<String>, + pub(super) client_secret: Secret<String>, + pub(super) payer_id: Secret<String>, +} + +impl PaypalAuthType { + pub fn get_credentials( + &self, + ) -> CustomResult<&PaypalConnectorCredentials, errors::ConnectorError> { + match self { + Self::TemporaryAuth => Err(errors::ConnectorError::InvalidConnectorConfig { + config: "TemporaryAuth found in connector_account_details", + } + .into()), + Self::AuthWithDetails(credentials) => Ok(credentials), + } + } +} + +impl TryFrom<&ConnectorAuthType> for PaypalAuthType { 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::BodyKey { api_key, key1 } => Ok(Self { - api_key: api_key.to_owned(), - key1: key1.to_owned(), - }), + types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::AuthWithDetails( + PaypalConnectorCredentials::StandardIntegration(StandardFlowCredentials { + client_id: key1.to_owned(), + client_secret: api_key.to_owned(), + }), + )), + types::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self::AuthWithDetails( + PaypalConnectorCredentials::PartnerIntegration(PartnerFlowCredentials { + client_id: key1.to_owned(), + client_secret: api_key.to_owned(), + payer_id: api_secret.to_owned(), + }), + )), + types::ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } }
2023-10-18T14:16:43Z
## 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 PayPal support `SignatureKey` `auth_type`. - Add extra fields in `orders` 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 <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To support PayPal onboarding flow. ## 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)? --> Postman. ### Payment Connector - Create Paypal now supports `TemporaryAuth` in the `auth_type`. You can find more details about this in this PR #2833. Paypal also support `SignatureKey` in the `auth_type`. ``` curl --location 'http://localhost:8080/account/merchant_1700133263/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "paypal", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "client_secret", "key1": "client_id", "api_secret": "partner_id" }, "status": "active", "disabled": false }' ``` If all the fields are passed correctly you will a normal mca response. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
938b63a1fceb87b4aae4211dac4d051e024028b1
juspay/hyperswitch
juspay__hyperswitch-2899
Bug: [BUG]: MCA metadata deserialization failures should be 4xx ### :memo: Feature Description - We don't have validation for Merchant Connector Account metadata, So while creating MCA we are allowing any json value. Because of which RequestEncodingFailure happening during payments for the MCA which doesn't have the expected fields. - Recreating scenario : Create a merchant connector account for coinbase with empty metadata .It doesn't throw error as we don't have metadata validation for coinbase . If you try to make payment now this will throw deserilization error for `CoinbaseConnectorMeta` which is merchant connector metadata for coinbase . ### :hammer: Possible Implementation - In the event of a deserialization failure of MCA metadata during payments and refunds, convert the ParsingFailed error to ConnectorError::InvalidConnectorConfig. - We already have authType validation in core/admin.rs , we need similar validation for connector metadata for coinbase . - Make sure that the config field in ConnectorError::InvalidConnectorConfig specifies the invalid configuration name. - Note that the ConnectorError::InvalidConnectorConfig error is already associated with [HTTP 400](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400) in the core. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2746 :bookmark: Note: All the changes needed should be contained within `/hyperswitch_oss/crates/router/src/connector/utils.rs` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index ce9bb3e871c..b1435e50df9 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +use common_utils::pii; +use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use crate::{ @@ -250,6 +252,14 @@ pub struct CoinbaseConnectorMeta { pub pricing_type: String, } +impl TryFrom<&Option<pii::SecretSerdeValue>> for CoinbaseConnectorMeta { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { + utils::to_connector_meta_from_secret(meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" }) + } +} + fn get_crypto_specific_payment_data( item: &types::PaymentsAuthorizeRouterData, ) -> Result<CoinbasePaymentsRequest, error_stack::Report<errors::ConnectorError>> { @@ -260,11 +270,10 @@ fn get_crypto_specific_payment_data( let name = billing_address.and_then(|add| add.get_first_name().ok().map(|name| name.to_owned())); let description = item.get_description().ok(); - let connector_meta: CoinbaseConnectorMeta = - utils::to_connector_meta_from_secret_with_required_field( - item.connector_meta_data.clone(), - "Pricing Type Not present in connector meta data", - )?; + let connector_meta = CoinbaseConnectorMeta::try_from(&item.connector_meta_data) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "Merchant connector account metadata", + })?; let pricing_type = connector_meta.pricing_type; let local_price = get_local_price(item); let redirect_url = item.request.get_return_url()?; diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 8f028e37a9e..9df11a6dd14 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1198,23 +1198,6 @@ where json.parse_value(std::any::type_name::<T>()).switch() } -pub fn to_connector_meta_from_secret_with_required_field<T>( - connector_meta: Option<Secret<serde_json::Value>>, - error_message: &'static str, -) -> Result<T, Error> -where - T: serde::de::DeserializeOwned, -{ - let connector_error = errors::ConnectorError::MissingRequiredField { - field_name: error_message, - }; - let parsed_meta = to_connector_meta_from_secret(connector_meta).ok(); - match parsed_meta { - Some(meta) => Ok(meta), - _ => Err(connector_error.into()), - } -} - pub fn to_connector_meta_from_secret<T>( connector_meta: Option<Secret<serde_json::Value>>, ) -> Result<T, Error> diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index fd4cae3a2b9..364c5b9b212 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1713,9 +1713,9 @@ pub(crate) fn validate_auth_and_metadata_type( checkout::transformers::CheckoutAuthType::try_from(val)?; Ok(()) } - api_enums::Connector::Coinbase => { coinbase::transformers::CoinbaseAuthType::try_from(val)?; + coinbase::transformers::CoinbaseConnectorMeta::try_from(connector_meta_data)?; Ok(()) } api_enums::Connector::Cryptopay => {
2023-12-19T12:53:56Z
## 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 --> I've removed `to_connector_meta_from_secret_with_required_field`, which uses `MissingRequiredField` as an error (I also didn't like the unnecessary initialization of the `MissingRequiredField` before we knew if it would be needed). Instead, I added a `TryFrom` implementation for `CoinbaseConnectorMeta`, which uses the requested `ConnectorError::InvalidConnectorConfig`. Additionally, I included `CoinbaseConnectorMeta::try_from` in the `validate_auth_and_metadata_type` as suggested. ### Migration ``` -- The migration is for adding an empty `pricing_type` attribute for `CoinbaseConnectorMeta` where it is missing. UPDATE merchant_connector_account SET metadata = jsonb_insert( metadata, '{pricing_type}', '""', true ) WHERE connector_name = 'coinbase' AND NOT metadata ? 'pricing_type'; ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] 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). --> This PR addresses the bug from the issue: https://github.com/juspay/hyperswitch/issues/2899. ## 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 unit test:** ``` cargo test --release --package router --lib connector::coinbase::transformers::tests::coinbase_payments_request_try_from_works -- --exact ``` ![image](https://github.com/juspay/hyperswitch/assets/8159517/a296af9b-a454-4d9b-a8ad-1939a837f04b) ### Migration script test https://onecompiler.com/postgresql/3zz2tpkad **Test script with test data and run migration:** ```label=dsa CREATE TABLE merchant_connector_account ( id SERIAL PRIMARY KEY, connector_name VARCHAR(255) NOT NULL ); ALTER TABLE merchant_connector_account ADD COLUMN metadata JSONB DEFAULT NULL; -- insert test data INSERT INTO merchant_connector_account ( id, connector_name, metadata ) VALUES (1, 'coinbase', '{ "pricing_type": "fixed-rate" }'), (2, 'coinbase', '{ "whatever_attribute": "abc" }'), (3, 'coinbase', '{}'); -- Before select * from merchant_connector_account; -- Run migration: -- The migration is for adding an empty `pricing_type` attribute for `CoinbaseConnectorMeta` where it is missing. UPDATE merchant_connector_account SET metadata = jsonb_insert( metadata, '{pricing_type}', '""', true ) WHERE connector_name = 'coinbase' AND NOT metadata ? 'pricing_type'; -- After select * from merchant_connector_account; ``` **Output:** ``` Output: CREATE TABLE ALTER TABLE INSERT 0 3 id | connector_name | metadata ----+----------------+-------------------------------- 1 | coinbase | {"pricing_type": "fixed-rate"} 2 | coinbase | {"whatever_attribute": "abc"} 3 | coinbase | {} (3 rows) UPDATE 2 id | connector_name | metadata ----+----------------+--------------------------------------------------- 1 | coinbase | {"pricing_type": "fixed-rate"} 2 | coinbase | {"pricing_type": "", "whatever_attribute": "abc"} 3 | coinbase | {"pricing_type": ""} (3 rows) ``` **Run locally:** **Invalid metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/5e087dad-9dab-4441-a444-787d8e720c1a) **Empty metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/0f745195-0b0b-4276-aeba-c18ad11d3749) **Correct metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/a5fe8ffa-12d2-449d-8363-a214aadca2fb) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5a791aaf4dc05e8ffdb60464a03b6fc41f860581
juspay/hyperswitch
juspay__hyperswitch-2866
Bug: [REFACTOR] : [Worldline] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 6cb8862f69b..049453e325a 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -306,10 +306,9 @@ impl TryFrom<utils::CardIssuer> for Gateway { utils::CardIssuer::Master => Ok(Self::MasterCard), utils::CardIssuer::Discover => Ok(Self::Discover), utils::CardIssuer::Visa => Ok(Self::Visa), - _ => Err(errors::ConnectorError::NotSupported { - message: issuer.to_string(), - connector: "worldline", - } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("worldline"), + ) .into()), } }
2023-11-16T17:13:09Z
## 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 --> ### 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 resolves #2866 <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? No test cases required. As In this PR only error message have been changed from Not Supported error message to NotImplemented error message. <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
94897d841e25d0be8debdfe1ec674f28848e2ad4
juspay/hyperswitch
juspay__hyperswitch-2864
Bug: [REFACTOR] : [Volt] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index efed7c797c7..6f4c67dce8a 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -130,10 +130,9 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | api_models::payments::BankRedirectData::Trustly { .. } | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Volt", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Volt"), + ) .into()) } }, @@ -150,10 +149,9 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Volt", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Volt"), + ) .into()) } }
2023-11-15T17:01:47Z
## 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 --> ### 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 Resolves #2864 ## 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)? --> No test cases required. As In this PR only error message have been changed from Not Supported error message to NotImplemented error message. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
37ab392488350c22d1d1352edc90f46af25d40be
juspay/hyperswitch
juspay__hyperswitch-2983
Bug: [FEATURE] receive `card_holder_name` in confirm flow when using token for payment ### Feature Description Currently, even though `card_holder_name` was empty, `/confirm` would occur without any error. But few connectors require `card_holder_name` to be sent. ### Possible Implementation Add new object `CardTokenData` in `payment_method_data` object which can be used to send the `card_holder_name` during `/confirm` flow along with the token. The token will fetch the stored card from locker. If this response has a `card_holder_name`, then it proceeds as usual without any error. Else it will check whether any `CardTokenData` object inside `payment_method_data` is sent or not. If not then error is thrown, if present then we update the `card` object received from locker to include the `card_holder_name` passed in `CardTokenData` during `/confirm` flow ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 74559f8ed69..acb9bbdd6cd 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -717,6 +717,14 @@ pub struct Card { pub nick_name: Option<Secret<String>>, } +#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct CardToken { + /// The card holder's name + #[schema(value_type = String, example = "John Test")] + pub card_holder_name: Option<Secret<String>>, +} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { @@ -846,6 +854,7 @@ pub enum PaymentMethodData { Upi(UpiData), Voucher(VoucherData), GiftCard(Box<GiftCardData>), + CardToken(CardToken), } impl PaymentMethodData { @@ -873,7 +882,8 @@ impl PaymentMethodData { | Self::Reward | Self::Upi(_) | Self::Voucher(_) - | Self::GiftCard(_) => None, + | Self::GiftCard(_) + | Self::CardToken(_) => None, } } } @@ -1092,6 +1102,7 @@ pub enum AdditionalPaymentData { GiftCard {}, Voucher {}, CardRedirect {}, + CardToken {}, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] @@ -1660,6 +1671,7 @@ pub enum PaymentMethodDataResponse { Voucher, GiftCard, CardRedirect, + CardToken, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -2455,6 +2467,7 @@ impl From<AdditionalPaymentData> for PaymentMethodDataResponse { AdditionalPaymentData::Voucher {} => Self::Voucher, AdditionalPaymentData::GiftCard {} => Self::GiftCard, AdditionalPaymentData::CardRedirect {} => Self::CardRedirect, + AdditionalPaymentData::CardToken {} => Self::CardToken, } } } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index f56369ed31a..66aeb3bb6b2 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -409,7 +409,8 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.router_data.payment_method), connector: "Aci", })?, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index a75e3b8ff17..a130ac50cc0 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1380,7 +1380,8 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> payments::PaymentMethodData::Crypto(_) | payments::PaymentMethodData::MandatePayment | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) => { + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Adyen", @@ -2276,7 +2277,8 @@ impl<'a> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), connector: "Adyen", diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 457b8d07548..3785e02d474 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -196,7 +196,8 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), )), }?; diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 70db9a6d879..12170deb1a0 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -410,7 +410,8 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Bank of America"), ) diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index fe92c337a01..b4ed314e706 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -221,7 +221,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::CardRedirect(_) | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( "Selected payment method via Token flow through bluesnap".to_string(), )) @@ -240,160 +241,160 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly, _ => BluesnapTxnType::AuthCapture, }; - let (payment_method, card_holder_info) = - match item.router_data.request.payment_method_data.clone() { - api::PaymentMethodData::Card(ref ccard) => Ok(( - PaymentMethodDetails::CreditCard(Card { - card_number: ccard.card_number.clone(), - expiration_month: ccard.card_exp_month.clone(), - expiration_year: ccard.get_expiry_year_4_digit(), - security_code: ccard.card_cvc.clone(), - }), - get_card_holder_info( - item.router_data.get_billing_address()?, - item.router_data.request.get_email()?, - )?, - )), - api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { - api_models::payments::WalletData::GooglePay(payment_method_data) => { - let gpay_object = - Encode::<BluesnapGooglePayObject>::encode_to_string_of_json( - &BluesnapGooglePayObject { - payment_method_data: utils::GooglePayWalletData::from( - payment_method_data, - ), - }, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(( - PaymentMethodDetails::Wallet(BluesnapWallet { - wallet_type: BluesnapWalletTypes::GooglePay, - encoded_payment_token: Secret::new( - consts::BASE64_ENGINE.encode(gpay_object), - ), - }), - None, - )) + let (payment_method, card_holder_info) = match item + .router_data + .request + .payment_method_data + .clone() + { + api::PaymentMethodData::Card(ref ccard) => Ok(( + PaymentMethodDetails::CreditCard(Card { + card_number: ccard.card_number.clone(), + expiration_month: ccard.card_exp_month.clone(), + expiration_year: ccard.get_expiry_year_4_digit(), + security_code: ccard.card_cvc.clone(), + }), + get_card_holder_info( + item.router_data.get_billing_address()?, + item.router_data.request.get_email()?, + )?, + )), + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + api_models::payments::WalletData::GooglePay(payment_method_data) => { + let gpay_object = Encode::<BluesnapGooglePayObject>::encode_to_string_of_json( + &BluesnapGooglePayObject { + payment_method_data: utils::GooglePayWalletData::from( + payment_method_data, + ), + }, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(( + PaymentMethodDetails::Wallet(BluesnapWallet { + wallet_type: BluesnapWalletTypes::GooglePay, + encoded_payment_token: Secret::new( + consts::BASE64_ENGINE.encode(gpay_object), + ), + }), + None, + )) + } + api_models::payments::WalletData::ApplePay(payment_method_data) => { + let apple_pay_payment_data = payment_method_data + .get_applepay_decoded_payment_data() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data + .expose()[..] + .as_bytes() + .parse_struct("ApplePayEncodedPaymentData") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let billing = item + .router_data + .address + .billing + .to_owned() + .get_required_value("billing") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "billing", + })?; + + let billing_address = billing + .address + .get_required_value("billing_address") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "billing", + })?; + + let mut address = Vec::new(); + if let Some(add) = billing_address.line1.to_owned() { + address.push(add) } - api_models::payments::WalletData::ApplePay(payment_method_data) => { - let apple_pay_payment_data = payment_method_data - .get_applepay_decoded_payment_data() - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - let apple_pay_payment_data: ApplePayEncodedPaymentData = - apple_pay_payment_data.expose()[..] - .as_bytes() - .parse_struct("ApplePayEncodedPaymentData") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - let billing = item - .router_data - .address - .billing - .to_owned() - .get_required_value("billing") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "billing", - })?; - - let billing_address = billing - .address - .get_required_value("billing_address") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "billing", - })?; - - let mut address = Vec::new(); - if let Some(add) = billing_address.line1.to_owned() { - address.push(add) - } - if let Some(add) = billing_address.line2.to_owned() { - address.push(add) - } - if let Some(add) = billing_address.line3.to_owned() { - address.push(add) - } - - let apple_pay_object = - Encode::<EncodedPaymentToken>::encode_to_string_of_json( - &EncodedPaymentToken { - token: ApplepayPaymentData { - payment_data: apple_pay_payment_data, - payment_method: payment_method_data - .payment_method - .to_owned() - .into(), - transaction_identifier: payment_method_data - .transaction_identifier, - }, - billing_contact: BillingDetails { - country_code: billing_address.country, - address_lines: Some(address), - family_name: billing_address.last_name.to_owned(), - given_name: billing_address.first_name.to_owned(), - postal_code: billing_address.zip, - }, - }, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - Ok(( - PaymentMethodDetails::Wallet(BluesnapWallet { - wallet_type: BluesnapWalletTypes::ApplePay, - encoded_payment_token: Secret::new( - consts::BASE64_ENGINE.encode(apple_pay_object), - ), - }), - get_card_holder_info( - item.router_data.get_billing_address()?, - item.router_data.request.get_email()?, - )?, - )) + if let Some(add) = billing_address.line2.to_owned() { + address.push(add) } - payments::WalletData::AliPayQr(_) - | payments::WalletData::AliPayRedirect(_) - | payments::WalletData::AliPayHkRedirect(_) - | payments::WalletData::MomoRedirect(_) - | payments::WalletData::KakaoPayRedirect(_) - | payments::WalletData::GoPayRedirect(_) - | payments::WalletData::GcashRedirect(_) - | payments::WalletData::ApplePayRedirect(_) - | payments::WalletData::ApplePayThirdPartySdk(_) - | payments::WalletData::DanaRedirect {} - | payments::WalletData::GooglePayRedirect(_) - | payments::WalletData::GooglePayThirdPartySdk(_) - | payments::WalletData::MbWayRedirect(_) - | payments::WalletData::MobilePayRedirect(_) - | payments::WalletData::PaypalRedirect(_) - | payments::WalletData::PaypalSdk(_) - | payments::WalletData::SamsungPay(_) - | payments::WalletData::TwintRedirect {} - | payments::WalletData::VippsRedirect {} - | payments::WalletData::TouchNGoRedirect(_) - | payments::WalletData::WeChatPayRedirect(_) - | payments::WalletData::CashappQr(_) - | payments::WalletData::SwishQr(_) - | payments::WalletData::WeChatPayQr(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("bluesnap"), - )) + if let Some(add) = billing_address.line3.to_owned() { + address.push(add) } - }, - payments::PaymentMethodData::PayLater(_) - | payments::PaymentMethodData::BankRedirect(_) - | payments::PaymentMethodData::BankDebit(_) - | payments::PaymentMethodData::BankTransfer(_) - | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::MandatePayment - | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) - | payments::PaymentMethodData::CardRedirect(_) - | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + + let apple_pay_object = Encode::<EncodedPaymentToken>::encode_to_string_of_json( + &EncodedPaymentToken { + token: ApplepayPaymentData { + payment_data: apple_pay_payment_data, + payment_method: payment_method_data + .payment_method + .to_owned() + .into(), + transaction_identifier: payment_method_data.transaction_identifier, + }, + billing_contact: BillingDetails { + country_code: billing_address.country, + address_lines: Some(address), + family_name: billing_address.last_name.to_owned(), + given_name: billing_address.first_name.to_owned(), + postal_code: billing_address.zip, + }, + }, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + Ok(( + PaymentMethodDetails::Wallet(BluesnapWallet { + wallet_type: BluesnapWalletTypes::ApplePay, + encoded_payment_token: Secret::new( + consts::BASE64_ENGINE.encode(apple_pay_object), + ), + }), + get_card_holder_info( + item.router_data.get_billing_address()?, + item.router_data.request.get_email()?, + )?, + )) + } + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayRedirect(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) + | payments::WalletData::WeChatPayQr(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), )) } - }?; + }, + payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("bluesnap"), + )), + }?; Ok(Self { amount: item.amount.to_owned(), payment_method, diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index 5069a9fe38d..009177e961e 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -138,7 +138,8 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("braintree"), ) @@ -879,12 +880,11 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("braintree"), - ) - .into()) - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("braintree"), + ) + .into()), } } } @@ -1423,9 +1423,10 @@ fn get_braintree_redirect_form( | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => Err( - errors::ConnectorError::NotImplemented("given payment method".to_owned()), - )?, + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + "given payment method".to_owned(), + ))?, }, }) } diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 90e65c8b047..173ac0b8f58 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -138,7 +138,8 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::CardRedirect(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), ) @@ -375,11 +376,10 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::CardRedirect(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("checkout"), - )) - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("checkout"), + )), }?; let three_ds = match item.router_data.auth_type { diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 0bc4ff3b3ae..446da0761d1 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -80,7 +80,8 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | api_models::payments::PaymentMethodData::Reward {} | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "CryptoPay", diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 33b8fa56d00..656c45b6d6b 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -367,7 +367,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ))? diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 668a335cce8..a9033e53d66 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -168,7 +168,8 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( crate::connector::utils::get_unimplemented_payment_method_error_message("Dlocal"), ))?, } diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index dd78324c9b8..2197b4558a2 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -112,7 +112,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { | api_models::payments::PaymentMethodData::Reward {} | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Forte", diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index 72204b51151..63e199657af 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -108,7 +108,8 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for GocardlessCustomerRequest | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Gocardless"), )) @@ -297,12 +298,11 @@ impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount { | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Gocardless"), - ) - .into()) - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Gocardless"), + ) + .into()), } } } @@ -483,11 +483,10 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest { | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - "Setup Mandate flow for selected payment method through Gocardless".to_string(), - )) - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + "Setup Mandate flow for selected payment method through Gocardless".to_string(), + )), }?; let payment_method_token = item.get_payment_method_token()?; let customer_bank_account = match payment_method_token { diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index 9510ff6e67a..9f405e2e2ea 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -141,7 +141,8 @@ impl TryFrom<&types::SetupMandateRouterData> for HelcimVerifyRequest { | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Helcim", @@ -223,12 +224,11 @@ impl TryFrom<&HelcimRouterData<&types::PaymentsAuthorizeRouterData>> for HelcimP | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.router_data.request.payment_method_data), - connector: "Helcim", - })? - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { + message: format!("{:?}", item.router_data.request.payment_method_data), + connector: "Helcim", + })?, } } } diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 3bd3407c3ae..91eaf94c01e 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -406,7 +406,8 @@ impl | api_payments::PaymentMethodData::Reward | api_payments::PaymentMethodData::Upi(_) | api_payments::PaymentMethodData::Voucher(_) - | api_payments::PaymentMethodData::GiftCard(_) => Err(error_stack::report!( + | api_payments::PaymentMethodData::GiftCard(_) + | api_payments::PaymentMethodData::CardToken(_) => Err(error_stack::report!( errors::ConnectorError::MismatchedPaymentData )), } diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index a067818b743..1780b77379c 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -365,7 +365,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }; @@ -509,7 +510,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }; diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 2af3ee0a1bb..15cbe9a7e28 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -624,7 +624,8 @@ fn get_payment_details_and_product( | PaymentMethodData::Reward | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) - | PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nexinets"), ))?, } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index c8721d0d8f6..ff3a1e6a1c5 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -188,7 +188,8 @@ impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "nmi", }) diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 5ff92582051..ee3a8ba8c53 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -284,7 +284,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { | api::PaymentMethodData::Reward {} | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => { + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Noon", diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index b79b2c89264..36244b8bc0d 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -856,8 +856,9 @@ impl<F> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::CardRedirect(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), ) @@ -1037,6 +1038,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, String)> for NuveiPay | Some(api::PaymentMethodData::CardRedirect(..)) | Some(api::PaymentMethodData::Reward) | Some(api::PaymentMethodData::Upi(..)) + | Some(api::PaymentMethodData::CardToken(..)) | None => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), )), diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index 41bcc1500ed..5e9fb066c78 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -52,7 +52,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Opayo"), ) .into()), diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 817ab43ac71..90c58c3a9bc 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -260,7 +260,8 @@ fn get_payment_method_data( | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Payeezy"), ))?, } diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 092a8b49fd8..e751de20e21 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -431,7 +431,8 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod { | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) => { + | PaymentMethodData::Voucher(_) + | PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } } @@ -666,7 +667,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("payme"), ))?, } @@ -725,6 +727,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { | Some(api::PaymentMethodData::Upi(_)) | Some(api::PaymentMethodData::Voucher(_)) | Some(api::PaymentMethodData::GiftCard(_)) + | Some(api::PaymentMethodData::CardToken(_)) | None => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } @@ -761,7 +764,8 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => { + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index d023077ff00..e59ff09a1f6 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -584,7 +584,8 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP } api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Crypto(_) - | api_models::payments::PaymentMethodData::Upi(_) => { + | api_models::payments::PaymentMethodData::Upi(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Paypal", diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 7f62c1939c0..a631a126ed3 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -113,7 +113,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "powertranz", }) diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 0dd3b858349..c272a5b6fc1 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -166,11 +166,14 @@ impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::Payme | payments::PaymentMethodData::Crypto(_) | payments::PaymentMethodData::MandatePayment | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Shift4", + } + .into()) } - .into()), } } } @@ -397,6 +400,7 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme | Some(payments::PaymentMethodData::Voucher(_)) | Some(payments::PaymentMethodData::Reward) | Some(payments::PaymentMethodData::Upi(_)) + | Some(api::PaymentMethodData::CardToken(_)) | None => Err(errors::ConnectorError::NotSupported { message: "Flow".to_string(), connector: "Shift4", diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index dfb49e8e677..6024a20fa6a 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -191,7 +191,8 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { | api::PaymentMethodData::MandatePayment | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Square", })?, @@ -307,7 +308,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { | api::PaymentMethodData::MandatePayment | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Square", })?, diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index f2aae442ddd..bb37bf1fc9e 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -118,7 +118,8 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme | api::PaymentMethodData::Voucher(_) | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) - | api::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: "SELECTED_PAYMENT_METHOD".to_string(), connector: "Stax", })?, @@ -268,7 +269,8 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { | api::PaymentMethodData::Voucher(_) | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) - | api::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: "SELECTED_PAYMENT_METHOD".to_string(), connector: "Stax", })?, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 56eebc2df3b..ae7fe59be96 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1431,13 +1431,13 @@ fn create_stripe_payment_method( .into()), }, - payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::MandatePayment => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } - .into()) + payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { + message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), + connector: "stripe", } + .into()), } } @@ -2995,6 +2995,7 @@ impl TryFrom<&types::PaymentsPreProcessingRouterData> for StripeCreditTransferSo | Some(payments::PaymentMethodData::GiftCard(..)) | Some(payments::PaymentMethodData::CardRedirect(..)) | Some(payments::PaymentMethodData::Voucher(..)) + | Some(payments::PaymentMethodData::CardToken(..)) | None => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) @@ -3416,7 +3417,8 @@ impl | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::CardRedirect(_) - | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: format!("{pm_type:?}"), connector: "Stripe", })?, diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 0210d3ca2d9..e891501d6d0 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -445,7 +445,8 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpay"), ) .into()), diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index c60aeb64898..863b754fc89 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -77,7 +77,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("tsys"), ))?, } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index e603ef2db06..efed7c797c7 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -148,7 +148,8 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Volt", diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 049453e325a..282e1b3a8ad 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -257,7 +257,8 @@ impl | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldline"), ))?, }; diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index d31f4d65e78..e35a51552c0 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -120,7 +120,8 @@ fn fetch_payment_instrument( | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::CardRedirect(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldpay"), ) diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 689894176b2..64f6d5bf1a0 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -707,7 +707,8 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment api_models::payments::PaymentMethodData::Crypto(_) | api_models::payments::PaymentMethodData::MandatePayment | api_models::payments::PaymentMethodData::Reward - | api_models::payments::PaymentMethodData::Upi(_) => { + | api_models::payments::PaymentMethodData::Upi(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Zen"), ))? diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 80cec01e916..1049137a947 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -3,6 +3,7 @@ pub mod surcharge_decision_configs; pub mod transformers; pub mod vault; +use api_models::payments::CardToken; pub use api_models::{ enums::{Connector, PayoutConnectors}, payouts as payout_types, @@ -42,6 +43,7 @@ pub trait PaymentMethodRetrieve { token: &storage::PaymentTokenData, payment_intent: &PaymentIntent, card_cvc: Option<masking::Secret<String>>, + card_token_data: Option<&CardToken>, ) -> RouterResult<Option<(payments::PaymentMethodData, enums::PaymentMethod)>>; } @@ -125,6 +127,7 @@ impl PaymentMethodRetrieve for Oss { token_data: &storage::PaymentTokenData, payment_intent: &PaymentIntent, card_cvc: Option<masking::Secret<String>>, + card_token_data: Option<&CardToken>, ) -> RouterResult<Option<(payments::PaymentMethodData, enums::PaymentMethod)>> { match token_data { storage::PaymentTokenData::TemporaryGeneric(generic_token) => { @@ -134,6 +137,7 @@ impl PaymentMethodRetrieve for Oss { payment_intent, card_cvc, merchant_key_store, + card_token_data, ) .await } @@ -145,6 +149,7 @@ impl PaymentMethodRetrieve for Oss { payment_intent, card_cvc, merchant_key_store, + card_token_data, ) .await } @@ -155,6 +160,7 @@ impl PaymentMethodRetrieve for Oss { &card_token.token, payment_intent, card_cvc, + card_token_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) @@ -166,6 +172,7 @@ impl PaymentMethodRetrieve for Oss { &card_token.token, payment_intent, card_cvc, + card_token_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index f57c0640f1a..68b8128d790 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use api_models::payments::GetPaymentMethodType; +use api_models::payments::{CardToken, GetPaymentMethodType}; use base64::Engine; use common_utils::{ ext_traits::{AsyncExt, ByteSliceExt, ValueExt}, @@ -1356,6 +1356,7 @@ pub async fn retrieve_payment_method_with_temporary_token( payment_intent: &PaymentIntent, card_cvc: Option<masking::Secret<String>>, merchant_key_store: &domain::MerchantKeyStore, + card_token_data: Option<&CardToken>, ) -> RouterResult<Option<(api::PaymentMethodData, enums::PaymentMethod)>> { let (pm, supplementary_data) = vault::Vault::get_payment_method_data_from_locker(state, token, merchant_key_store) @@ -1375,9 +1376,29 @@ pub async fn retrieve_payment_method_with_temporary_token( Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm { Some(api::PaymentMethodData::Card(card)) => { + let mut updated_card = card.clone(); + let mut is_card_updated = false; + + let name_on_card = if card.card_holder_name.clone().expose().is_empty() { + card_token_data + .and_then(|token_data| { + is_card_updated = true; + token_data.card_holder_name.clone() + }) + .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "card_holder_name", + })? + } else { + card.card_holder_name.clone() + }; + updated_card.card_holder_name = name_on_card; + if let Some(cvc) = card_cvc { - let mut updated_card = card; + is_card_updated = true; updated_card.card_cvc = cvc; + } + if is_card_updated { let updated_pm = api::PaymentMethodData::Card(updated_card); vault::Vault::store_payment_method_data_in_locker( state, @@ -1423,6 +1444,7 @@ pub async fn retrieve_card_with_permanent_token( token: &str, payment_intent: &PaymentIntent, card_cvc: Option<masking::Secret<String>>, + card_token_data: Option<&CardToken>, ) -> RouterResult<api::PaymentMethodData> { let customer_id = payment_intent .customer_id @@ -1437,13 +1459,26 @@ pub async fn retrieve_card_with_permanent_token( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?; + let name = card + .name_on_card + .get_required_value("name_on_card") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("card holder name was not saved in permanent locker")?; + + let name_on_card = if name.clone().expose().is_empty() { + card_token_data + .and_then(|token_data| token_data.card_holder_name.clone()) + .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "card_holder_name", + })? + } else { + name + }; + let api_card = api::Card { card_number: card.card_number, - card_holder_name: card - .name_on_card - .get_required_value("name_on_card") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("card holder name was not saved in permanent locker")?, + card_holder_name: name_on_card, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_cvc: card_cvc.unwrap_or_default(), @@ -1529,6 +1564,11 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>( let card_cvc = payment_data.card_cvc.clone(); + let card_token_data = request.as_ref().and_then(|pmd| match pmd { + api_models::payments::PaymentMethodData::CardToken(token_data) => Some(token_data), + _ => None, + }); + // TODO: Handle case where payment method and token both are present in request properly. let payment_method = match (request, hyperswitch_token) { (_, Some(hyperswitch_token)) => { @@ -1538,6 +1578,7 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>( &hyperswitch_token, &payment_data.payment_intent, card_cvc, + card_token_data, ) .await .attach_printable("in 'make_pm_data'")?; @@ -3316,6 +3357,9 @@ pub async fn get_additional_payment_data( api_models::payments::PaymentMethodData::GiftCard(_) => { api_models::payments::AdditionalPaymentData::GiftCard {} } + api_models::payments::PaymentMethodData::CardToken(_) => { + api_models::payments::AdditionalPaymentData::CardToken {} + } } } @@ -3615,6 +3659,12 @@ pub fn get_key_params_for_surcharge_details( gift_card.get_payment_method_type(), None, )), + api_models::payments::PaymentMethodData::CardToken(_) => { + Err(errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_method_data", + } + .into()) + } } } diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index d191890b8cd..ec38389cdc4 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -248,6 +248,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::OnlineMandate, api_models::payments::Card, api_models::payments::CardRedirectData, + api_models::payments::CardToken, api_models::payments::CustomerAcceptance, api_models::payments::PaymentsRequest, api_models::payments::PaymentsCreateRequest, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 45aad93371e..5bd28db3c15 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -522,7 +522,8 @@ impl ForeignTryFrom<api_models::payments::PaymentMethodData> for api_enums::Paym payment_method_data: api_models::payments::PaymentMethodData, ) -> Result<Self, Self::Error> { match payment_method_data { - api_models::payments::PaymentMethodData::Card(..) => Ok(Self::Card), + api_models::payments::PaymentMethodData::Card(..) + | api_models::payments::PaymentMethodData::CardToken(..) => Ok(Self::Card), api_models::payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet), api_models::payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater), api_models::payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect), diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 88a0d115ff0..08f41578296 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4053,6 +4053,19 @@ } ] }, + "CardToken": { + "type": "object", + "required": [ + "card_holder_name" + ], + "properties": { + "card_holder_name": { + "type": "string", + "description": "The card holder's name", + "example": "John Test" + } + } + }, "CashappQr": { "type": "object" }, @@ -8657,6 +8670,17 @@ "$ref": "#/components/schemas/GiftCardData" } } + }, + { + "type": "object", + "required": [ + "card_token" + ], + "properties": { + "card_token": { + "$ref": "#/components/schemas/CardToken" + } + } } ] },
2023-11-25T14:20:31Z
## 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, even though `card_holder_name` was empty, `/confirm` would occur without any error. But few connectors require `card_holder_name` to be sent. This PR includes changes for adding new object `CardToken` in `payment_method_data` object which can be used to send the `card_holder_name` during `/confirm` flow along with the token. The token will fetch the stored card from locker. If this response has a `card_holder_name`, then it proceeds as usual without any error. Else it will check whether any `CardToken` object inside `payment_method_data` is sent or not. If not then error is thrown, if present then we update the `card` object received from locker to include the `card_holder_name` passed in `CardToken` during `/confirm` flow ### 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. Make a payment with saving the card. pass card_holder_name empty while saving ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_u67d5zdpJVfHQ5jRhWXNg5F0Wy8MhzG2STAeHBhIKJowJJxAuVtvwhB2lsL427C8' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "business_label": "default", "business_country": "US" }' ``` 2. Do `list_customer_payment_method` to get the `payment_token` 3. Now when you use that token to do payment again, you will get below error ![image](https://github.com/juspay/hyperswitch/assets/70657455/e4cfbd6b-a0fd-4e76-89d7-853a39fe1f78) 4. Now pass the `payment_method_data` object passing the `card_holder_name` here along with token in confirm call ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_u67d5zdpJVfHQ5jRhWXNg5F0Wy8MhzG2STAeHBhIKJowJJxAuVtvwhB2lsL427C8' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_token": "token_PLmf9CALewF4hxRSCkC4", "payment_method_data": { "card_token": { "card_holder_name": "Joseph" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "business_label": "default", "business_country": "US" }' ``` If you see the response from confirm call, the `payment_method_data` object will have the `card_holder_name` passed above ![image](https://github.com/juspay/hyperswitch/assets/70657455/fdba9c8b-b1d9-4ee9-ad0f-0f0cdb7bf2ed) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0e66b1b5dcce6dd87c9d743c9eb73d0cd8e330b2
juspay/hyperswitch
juspay__hyperswitch-2865
Bug: [REFACTOR] : [Wise] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs index c481f0c7343..e0fc05c3c89 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/router/src/connector/wise/transformers.rs @@ -11,7 +11,7 @@ type Error = error_stack::Report<errors::ConnectorError>; #[cfg(feature = "payouts")] use crate::{ - connector::utils::RouterData, + connector::utils::{self, RouterData}, types::{ api::payouts, storage::enums::{self as storage_enums, PayoutEntityType}, @@ -344,10 +344,9 @@ fn get_payout_bank_details( bic: b.bic, ..WiseBankDetails::default() }), - _ => Err(errors::ConnectorError::NotSupported { - message: "Card payout creation is not supported".to_string(), - connector: "Wise", - }), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, } } @@ -371,10 +370,9 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WiseRecipientCreateRequest { }), }?; match request.payout_type.to_owned() { - storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported { - message: "Card payout creation is not supported".to_string(), - connector: "Wise", - })?, + storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, storage_enums::PayoutType::Bank => { let account_holder_name = customer_details .ok_or(errors::ConnectorError::MissingRequiredField { @@ -432,10 +430,9 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutQuoteRequest { target_currency: request.destination_currency.to_string(), pay_out: WisePayOutOption::default(), }), - storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported { - message: "Card payout fulfillment is not supported".to_string(), - connector: "Wise", - })?, + storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } @@ -489,10 +486,9 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutCreateRequest { details: wise_transfer_details, }) } - storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported { - message: "Card payout fulfillment is not supported".to_string(), - connector: "Wise", - })?, + storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } @@ -533,10 +529,9 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutFulfillRequest { storage_enums::PayoutType::Bank => Ok(Self { fund_type: FundType::default(), }), - storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported { - message: "Card payout fulfillment is not supported".to_string(), - connector: "Wise", - })?, + storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } @@ -599,10 +594,9 @@ impl TryFrom<PayoutMethodData> for RecipientType { PayoutMethodData::Bank(api_models::payouts::Bank::Ach(_)) => Ok(Self::Aba), PayoutMethodData::Bank(api_models::payouts::Bank::Bacs(_)) => Ok(Self::SortCode), PayoutMethodData::Bank(api_models::payouts::Bank::Sepa(_)) => Ok(Self::Iban), - _ => Err(errors::ConnectorError::NotSupported { - message: "Requested payout_method_type is not supported".to_string(), - connector: "Wise", - } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ) .into()), } }
2023-11-22T14:59:35Z
## 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 --> ### 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6c15fc312345ed9520accb4d02b12688f98ba1a1
juspay/hyperswitch
juspay__hyperswitch-2863
Bug: [REFACTOR] : [Stripe] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 6a89232d4e8..03c424a219f 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -684,10 +684,9 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::FamilyMart | enums::PaymentMethodType::Seicomart | enums::PaymentMethodType::PayEasy - | enums::PaymentMethodType::Walley => Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } + | enums::PaymentMethodType::Walley => Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ) .into()), } } @@ -873,10 +872,9 @@ impl TryFrom<&api_models::enums::BankNames> for StripeBankNames { api_models::enums::BankNames::AliorBank => Self::AliorBank, api_models::enums::BankNames::Boz => Self::Boz, - _ => Err(errors::ConnectorError::NotSupported { - message: api_enums::PaymentMethod::BankRedirect.to_string(), - connector: "Stripe", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ))?, }) } } @@ -919,10 +917,9 @@ impl TryFrom<&api_models::payments::PayLaterData> for StripePaymentMethodType { | payments::PayLaterData::WalleyRedirect {} | payments::PayLaterData::AlmaRedirect {} | payments::PayLaterData::AtomeRedirect {} => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - }) + Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + )) } } } @@ -953,10 +950,9 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodType { | payments::BankRedirectData::OnlineBankingThailand { .. } | payments::BankRedirectData::OpenBankingUk { .. } | payments::BankRedirectData::Trustly { .. } => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - }) + Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + )) } } } @@ -996,10 +992,9 @@ impl ForeignTryFrom<&payments::WalletData> for Option<StripePaymentMethodType> { | payments::WalletData::TouchNGoRedirect(_) | payments::WalletData::SwishQr(_) | payments::WalletData::WeChatPayRedirect(_) => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - }) + Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + )) } } } @@ -1398,10 +1393,9 @@ fn create_stripe_payment_method( | payments::BankTransferData::CimbVaBankTransfer { .. } | payments::BankTransferData::DanamonVaBankTransfer { .. } | payments::BankTransferData::MandiriVaBankTransfer { .. } => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } + Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ) .into()) } } @@ -1413,10 +1407,9 @@ fn create_stripe_payment_method( payments::PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() { payments::GiftCardData::Givex(_) | payments::GiftCardData::PaySafeCard {} => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } + Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ) .into()) } }, @@ -1426,10 +1419,9 @@ fn create_stripe_payment_method( | payments::CardRedirectData::Benefit {} | payments::CardRedirectData::MomoAtm {} | payments::CardRedirectData::CardRedirect {} => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } + Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ) .into()) } }, @@ -1456,19 +1448,17 @@ fn create_stripe_payment_method( | payments::VoucherData::MiniStop(_) | payments::VoucherData::FamilyMart(_) | payments::VoucherData::Seicomart(_) - | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } + | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ) .into()), }, payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::MandatePayment - | payments::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } + | payments::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ) .into()), } } @@ -1588,10 +1578,9 @@ impl TryFrom<(&payments::WalletData, Option<types::PaymentMethodToken>)> | payments::WalletData::TouchNGoRedirect(_) | payments::WalletData::SwishQr(_) | payments::WalletData::WeChatPayRedirect(_) => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } + Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ) .into()) } } @@ -1681,10 +1670,9 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData { | payments::BankRedirectData::OnlineBankingThailand { .. } | payments::BankRedirectData::OpenBankingUk { .. } | payments::BankRedirectData::Trustly { .. } => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } + Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ) .into()) } } @@ -3579,10 +3567,9 @@ impl | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{pm_type:?}"), - connector: "Stripe", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + connector_util::get_unimplemented_payment_method_error_message("stripe"), + ))?, } } }
2024-02-17T02:18:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Should close #2863 by changing `NotSupported` to `NotImplemented` error for Stripe ### 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? Test a Payment Method which is not implemented It should give Not implemented error This is an Crypto payment request. ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_data": { "crypto": {} }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "profile_id": "pro_16j8JOCurimvr2XXG9EE" } ``` This is a Payment Method which is not implemented for Stripe ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
783fa0b0dff1e157920d683a75fc579942cd9c06
juspay/hyperswitch
juspay__hyperswitch-2895
Bug: [FEATURE]: Add ability to add connectors without any auth details ### Feature Description Ability to integrate a connector without any auth details. But it need not be used for routing until we get the auth details. ### Possible Implementation Create a new auth_type, which doesn't need any details and use the disabled field in the mca table to disable it in routing. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 6b9928734ce..efde4a04832 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -609,6 +609,9 @@ pub struct MerchantConnectorCreate { pub profile_id: Option<String>, pub pm_auth_config: Option<serde_json::Value>, + + #[schema(value_type = ConnectorStatus, example = "inactive")] + pub status: Option<api_enums::ConnectorStatus>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] @@ -714,6 +717,9 @@ pub struct MerchantConnectorResponse { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + + #[schema(value_type = ConnectorStatus, example = "inactive")] + pub status: api_enums::ConnectorStatus, } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." @@ -788,6 +794,9 @@ pub struct MerchantConnectorUpdate { pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, pub pm_auth_config: Option<serde_json::Value>, + + #[schema(value_type = ConnectorStatus, example = "inactive")] + pub status: Option<api_enums::ConnectorStatus>, } ///Details of FrmConfigs are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 8b1437fa892..cf3c398f8f4 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1857,3 +1857,25 @@ pub enum ApplePayFlow { Simplified, Manual, } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + strum::Display, + strum::EnumString, + serde::Deserialize, + serde::Serialize, + ToSchema, + Default, +)] +#[router_derive::diesel_enum(storage_type = "pg_enum")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum ConnectorStatus { + #[default] + Inactive, + Active, +} diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index ec021f0f51a..817fee63319 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -3,9 +3,10 @@ pub mod diesel_exports { pub use super::{ DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, - DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, - DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, - DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, + DbConnectorStatus as ConnectorStatus, DbConnectorType as ConnectorType, + DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDisputeStage as DisputeStage, + DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, + DbEventObjectType as EventObjectType, DbEventType as EventType, DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index a4faa45ce4b..e45ef002626 100644 --- a/crates/diesel_models/src/merchant_connector_account.rs +++ b/crates/diesel_models/src/merchant_connector_account.rs @@ -42,6 +42,7 @@ pub struct MerchantConnectorAccount { #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + pub status: storage_enums::ConnectorStatus, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -70,6 +71,7 @@ pub struct MerchantConnectorAccountNew { #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + pub status: storage_enums::ConnectorStatus, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -93,6 +95,7 @@ pub struct MerchantConnectorAccountUpdateInternal { #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + pub status: Option<storage_enums::ConnectorStatus>, } impl MerchantConnectorAccountUpdateInternal { @@ -115,6 +118,7 @@ impl MerchantConnectorAccountUpdateInternal { frm_config: self.frm_config, modified_at: self.modified_at.unwrap_or(source.modified_at), pm_auth_config: self.pm_auth_config, + status: self.status.unwrap_or(source.status), ..source } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index e9db5714bed..190a123185e 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -492,6 +492,7 @@ diesel::table! { profile_id -> Nullable<Varchar>, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, + status -> ConnectorStatus, } } diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs index ecea12203f8..6105dc85d7e 100644 --- a/crates/kgraph_utils/benches/evaluation.rs +++ b/crates/kgraph_utils/benches/evaluation.rs @@ -65,6 +65,7 @@ fn build_test_data<'a>(total_enabled: usize, total_pm_types: usize) -> graph::Kn profile_id: None, applepay_verified_domains: None, pm_auth_config: None, + status: api_enums::ConnectorStatus::Inactive, }; kgraph_utils::mca::make_mca_graph(vec![stripe_account]).expect("Failed graph construction") diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 34babd7a02b..deea51bd880 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -410,6 +410,7 @@ mod tests { profile_id: None, applepay_verified_domains: None, pm_auth_config: None, + status: api_enums::ConnectorStatus::Inactive, }; make_mca_graph(vec![stripe_account]).expect("Failed graph construction") diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 54a7c461dbf..dfb49e8e677 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -334,6 +334,7 @@ impl TryFrom<&types::ConnectorAuthType> for SquareAuthType { | types::ConnectorAuthType::SignatureKey { .. } | types::ConnectorAuthType::MultiAuthKey { .. } | types::ConnectorAuthType::CurrencyAuthKey { .. } + | types::ConnectorAuthType::TemporaryAuth { .. } | types::ConnectorAuthType::NoKey { .. } => { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 39b4749535b..c921a9164cb 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -868,6 +868,15 @@ pub async fn create_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error updating the merchant account when creating payment connector")?; + let (connector_status, disabled) = validate_status_and_disabled( + req.status, + req.disabled, + auth, + // The validate_status_and_disabled function will use this value only + // when the status can be active. So we are passing this as fallback. + api_enums::ConnectorStatus::Active, + )?; + let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type, @@ -886,7 +895,7 @@ pub async fn create_payment_connector( .attach_printable("Unable to encrypt connector account details")?, payment_methods_enabled, test_mode: req.test_mode, - disabled: req.disabled, + disabled, metadata: req.metadata, frm_configs, connector_label: Some(connector_label), @@ -911,6 +920,7 @@ pub async fn create_payment_connector( profile_id: Some(profile_id.clone()), applepay_verified_domains: None, pm_auth_config: req.pm_auth_config.clone(), + status: connector_status, }; let mut default_routing_config = @@ -1083,6 +1093,19 @@ pub async fn update_payment_connector( let frm_configs = get_frm_config_as_secret(req.frm_configs); + let auth: types::ConnectorAuthType = req + .connector_account_details + .clone() + .unwrap_or(mca.connector_account_details.clone().into_inner()) + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_account_details".to_string(), + expected_format: "auth_type and api_key".to_string(), + })?; + + let (connector_status, disabled) = + validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?; + let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: None, connector_type: Some(req.connector_type), @@ -1098,7 +1121,7 @@ pub async fn update_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting data")?, test_mode: req.test_mode, - disabled: req.disabled, + disabled, payment_methods_enabled, metadata: req.metadata, frm_configs, @@ -1115,6 +1138,7 @@ pub async fn update_payment_connector( }, applepay_verified_domains: None, pm_auth_config: req.pm_auth_config, + status: Some(connector_status), }; let updated_mca = db @@ -1722,3 +1746,37 @@ pub async fn validate_dummy_connector_enabled( Ok(()) } } + +pub fn validate_status_and_disabled( + status: Option<api_enums::ConnectorStatus>, + disabled: Option<bool>, + auth: types::ConnectorAuthType, + current_status: api_enums::ConnectorStatus, +) -> RouterResult<(api_enums::ConnectorStatus, Option<bool>)> { + let connector_status = match (status, auth) { + (Some(common_enums::ConnectorStatus::Active), types::ConnectorAuthType::TemporaryAuth) => { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Connector status cannot be active when using TemporaryAuth".to_string(), + } + .into()); + } + (Some(status), _) => status, + (None, types::ConnectorAuthType::TemporaryAuth) => common_enums::ConnectorStatus::Inactive, + (None, _) => current_status, + }; + + let disabled = match (disabled, connector_status) { + (Some(true), common_enums::ConnectorStatus::Inactive) => { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth" + .to_string(), + } + .into()); + } + (Some(disabled), _) => Some(disabled), + (None, common_enums::ConnectorStatus::Inactive) => Some(true), + (None, _) => None, + }; + + Ok((connector_status, disabled)) +} diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs index 433430507fb..56960d3cb48 100644 --- a/crates/router/src/core/verification/utils.rs +++ b/crates/router/src/core/verification/utils.rs @@ -60,6 +60,7 @@ pub async fn check_existence_and_add_domain_to_db( applepay_verified_domains: Some(already_verified_domains.clone()), pm_auth_config: None, connector_label: None, + status: None, }; state .store diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index ecf52531f28..4fbb8f19ccf 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -643,6 +643,7 @@ impl MerchantConnectorAccountInterface for MockDb { profile_id: t.profile_id, applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, + status: t.status, }; accounts.push(account.clone()); account @@ -839,6 +840,7 @@ mod merchant_connector_account_cache_tests { profile_id: Some(profile_id.to_string()), applepay_verified_domains: None, pm_auth_config: None, + status: common_enums::ConnectorStatus::Inactive, }; db.insert_merchant_connector_account(mca.clone(), &merchant_key) diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 095e1f45f93..04ef90546cf 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -174,6 +174,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::AttemptStatus, api_models::enums::CaptureStatus, api_models::enums::ReconStatus, + api_models::enums::ConnectorStatus, api_models::admin::MerchantConnectorCreate, api_models::admin::MerchantConnectorUpdate, api_models::admin::PrimaryBusinessDetails, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 7cf8f6b71fa..ceeb93f6976 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -900,6 +900,7 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { #[derive(Default, Debug, Clone, serde::Deserialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { + TemporaryAuth, HeaderKey { api_key: Secret<String>, }, diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 58c2e018316..c84abbefc38 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -35,6 +35,7 @@ pub struct MerchantConnectorAccount { pub profile_id: Option<String>, pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + pub status: enums::ConnectorStatus, } #[derive(Debug)] @@ -54,6 +55,7 @@ pub enum MerchantConnectorAccountUpdate { applepay_verified_domains: Option<Vec<String>>, pm_auth_config: Option<serde_json::Value>, connector_label: Option<String>, + status: Option<enums::ConnectorStatus>, }, } @@ -89,6 +91,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { profile_id: self.profile_id, applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, + status: self.status, }, ) } @@ -128,6 +131,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { profile_id: other.profile_id, applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, + status: other.status, }) } @@ -155,6 +159,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { profile_id: self.profile_id, applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, + status: self.status, }) } } @@ -177,6 +182,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte applepay_verified_domains, pm_auth_config, connector_label, + status, } => Self { merchant_id, connector_type, @@ -194,6 +200,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte applepay_verified_domains, pm_auth_config, connector_label, + status, }, } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 3ffba5aff50..2b7ea86cf51 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -852,6 +852,7 @@ impl TryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantCo profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, + status: item.status, }) } } diff --git a/migrations/2023-11-12-131143_connector-status-column/down.sql b/migrations/2023-11-12-131143_connector-status-column/down.sql new file mode 100644 index 00000000000..9463f4d7713 --- /dev/null +++ b/migrations/2023-11-12-131143_connector-status-column/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS status; +DROP TYPE IF EXISTS "ConnectorStatus"; diff --git a/migrations/2023-11-12-131143_connector-status-column/up.sql b/migrations/2023-11-12-131143_connector-status-column/up.sql new file mode 100644 index 00000000000..7a992d142d6 --- /dev/null +++ b/migrations/2023-11-12-131143_connector-status-column/up.sql @@ -0,0 +1,11 @@ +-- Your SQL goes here +CREATE TYPE "ConnectorStatus" AS ENUM ('active', 'inactive'); + +ALTER TABLE merchant_connector_account +ADD COLUMN status "ConnectorStatus"; + +UPDATE merchant_connector_account SET status='active'; + +ALTER TABLE merchant_connector_account +ALTER COLUMN status SET NOT NULL, +ALTER COLUMN status SET DEFAULT 'inactive'; diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index be66a1bff92..7d94f13dd12 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4147,6 +4147,13 @@ } } }, + "ConnectorStatus": { + "type": "string", + "enum": [ + "inactive", + "active" + ] + }, "ConnectorType": { "type": "string", "enum": [ @@ -6871,7 +6878,8 @@ "description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", "required": [ "connector_type", - "connector_name" + "connector_name", + "status" ], "properties": { "connector_type": { @@ -7002,6 +7010,9 @@ }, "pm_auth_config": { "nullable": true + }, + "status": { + "$ref": "#/components/schemas/ConnectorStatus" } } }, @@ -7087,7 +7098,8 @@ "required": [ "connector_type", "connector_name", - "merchant_connector_id" + "merchant_connector_id", + "status" ], "properties": { "connector_type": { @@ -7230,6 +7242,9 @@ }, "pm_auth_config": { "nullable": true + }, + "status": { + "$ref": "#/components/schemas/ConnectorStatus" } } }, @@ -7237,7 +7252,8 @@ "type": "object", "description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", "required": [ - "connector_type" + "connector_type", + "status" ], "properties": { "connector_type": { @@ -7335,6 +7351,9 @@ }, "pm_auth_config": { "nullable": true + }, + "status": { + "$ref": "#/components/schemas/ConnectorStatus" } } },
2023-11-16T06:18:57Z
## 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 new `auth_type` called `TemporaryAuth` which describes that auth details are not yet received. When using this `auth_type` the connector status will be `inactive` and mca will be disabled. ### 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). --> To support connector integration without auth details. Closes #2895 ## 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)? --> Postman. Payment Connector - Create and Payment Connector - Update now supports a new auth type called `TemporaryAuth` and a new field `status`. ``` curl --location 'http://localhost:8080/account/merchant_1700133263/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "paypal", "connector_account_details": { "auth_type": "TemporaryAuth" }, "status": "inactive", "disabled": true }' ``` If `TemporaryAuth` is used in the request, the status field cannot be `active` and disabled cannot be `false`. This is applied for update mca as well. If a connector is inactive it cannot be enabled without changing the status to active. There are the following error messages that will be thrown if incorrect request is used. | auth_type | status | disabled | error_message | |---------------|----------|----------|-------------------------------------------------------------------------------------------| | TemoraryAuth | active | * | Connector status cannot be active when using TemporaryAuth | | TemporaryAuth | inactive | false | Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth | | ValidAuth | inactive | false | Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth | If all the fields are passed correctly you will a normal mca response. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
94897d841e25d0be8debdfe1ec674f28848e2ad4
juspay/hyperswitch
juspay__hyperswitch-2861
Bug: [REFACTOR] : [Square] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index e159b1d8ade..1e5501575ad 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -4,7 +4,7 @@ use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{CardData, PaymentsAuthorizeRequestData, RouterData}, + connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData}, core::errors, types::{ self, api, @@ -17,19 +17,14 @@ impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenReq fn try_from( value: (&types::TokenizationRouterData, BankDebitData), ) -> Result<Self, Self::Error> { - let (item, bank_debit_data) = value; + let (_item, bank_debit_data) = value; match bank_debit_data { - BankDebitData::AchBankDebit { .. } => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - - BankDebitData::SepaBankDebit { .. } + BankDebitData::AchBankDebit { .. } + | BankDebitData::SepaBankDebit { .. } | BankDebitData::BecsBankDebit { .. } - | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -82,23 +77,18 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ fn try_from( value: (&types::TokenizationRouterData, PayLaterData), ) -> Result<Self, Self::Error> { - let (item, pay_later_data) = value; + let (_item, pay_later_data) = value; match pay_later_data { - PayLaterData::AfterpayClearpayRedirect { .. } => Err( - errors::ConnectorError::NotImplemented("Payment Method".to_string()), - ) - .into_report(), - - PayLaterData::KlarnaRedirect { .. } + PayLaterData::AfterpayClearpayRedirect { .. } + | PayLaterData::KlarnaRedirect { .. } | PayLaterData::KlarnaSdk { .. } | PayLaterData::AffirmRedirect { .. } | PayLaterData::PayBrightRedirect { .. } | PayLaterData::WalleyRedirect { .. } | PayLaterData::AlmaRedirect { .. } - | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -106,18 +96,11 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: (&types::TokenizationRouterData, WalletData)) -> Result<Self, Self::Error> { - let (item, wallet_data) = value; + let (_item, wallet_data) = value; match wallet_data { - WalletData::ApplePay(_) => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - WalletData::GooglePay(_) => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - - WalletData::AliPayQr(_) + WalletData::ApplePay(_) + | WalletData::GooglePay(_) + | WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::MomoRedirect(_) @@ -140,10 +123,9 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) - | WalletData::SwishQr(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -180,11 +162,8 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { api::PaymentMethodData::PayLater(pay_later_data) => { Self::try_from((item, pay_later_data)) } - api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - api::PaymentMethodData::BankRedirect(_) + api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::BankRedirect(_) | api::PaymentMethodData::BankTransfer(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Crypto(_) @@ -192,10 +171,9 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -297,11 +275,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { api::PaymentMethodData::BankDebit(_) | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::PayLater(_) - | api::PaymentMethodData::Wallet(_) => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::BankRedirect(_) | api::PaymentMethodData::BankTransfer(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Crypto(_) @@ -309,10 +284,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } }
2023-11-15T11:06:58Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Consistent error messages for not implemented payment method. ## Motivation and Context Resolves #2861 ## How did you test it? payment connector create ``` { "connector_type": "fiz_operations", "connector_name": "volt", "connector_account_details": { "auth_type": "MultiAuthKey", "api_key": "{{connector_api_key}}", "api_secret": "{{connector_api_secret}}", "key1": "{{connector_key1}}", "key2": "{{connector_key2}}" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "open_banking_uk", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": false, "installment_payment_enabled": false // "accepted_currencies": { // "type": "enable_only", // "list": [ // "EUR" // ] // }, // "accepted_countries": { // "type": "enable_only", // "list": [ // "DE" // ] // } } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "dce1d767-7c28-429c-b0fe-9e0b9e91f962" }, "business_country": "US", "business_label": "food" } ``` create a payment which is not implemented Payment create ``` { "amount": 6540, "currency": "BRL", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": {} } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Make any payment for Square for any PM which is not implemented, and see for the error message - it should be payment method not implemented ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0666d814af93045ff23c85d8fd796da08cd5749b
juspay/hyperswitch
juspay__hyperswitch-2862
Bug: [REFACTOR] : [Stax] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index bb37bf1fc9e..5aa0949a09c 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -63,10 +63,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme item: &StaxRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if item.router_data.request.currency != enums::Currency::USD { - Err(errors::ConnectorError::NotSupported { - message: item.router_data.request.currency.to_string(), - connector: "Stax", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Stax"), + ))? } let total = item.amount; @@ -119,10 +118,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: "SELECTED_PAYMENT_METHOD".to_string(), - connector: "Stax", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Stax"), + ))?, } } } @@ -270,10 +268,9 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: "SELECTED_PAYMENT_METHOD".to_string(), - connector: "Stax", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Stax"), + ))?, } } }
2023-11-15T17:15:18Z
## 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 --> ### 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 Resolves #2862 ## 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)? --> No test cases required. As In this PR only error message have been changed from Not Supported error message to NotImplemented error message. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
37ab392488350c22d1d1352edc90f46af25d40be
juspay/hyperswitch
juspay__hyperswitch-2860
Bug: [REFACTOR] : [Shift4] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 606da2129fb..ce68aad25c5 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -168,10 +168,9 @@ impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::Payme | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()) } } @@ -184,13 +183,8 @@ impl TryFrom<&api_models::payments::WalletData> for Shift4PaymentMethod { match wallet_data { payments::WalletData::AliPayRedirect(_) | payments::WalletData::ApplePay(_) - | payments::WalletData::WeChatPayRedirect(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()) - } - payments::WalletData::AliPayQr(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::AliPayQr(_) | payments::WalletData::AliPayHkRedirect(_) | payments::WalletData::MomoRedirect(_) | payments::WalletData::KakaoPayRedirect(_) @@ -212,10 +206,9 @@ impl TryFrom<&api_models::payments::WalletData> for Shift4PaymentMethod { | payments::WalletData::TouchNGoRedirect(_) | payments::WalletData::WeChatPayQr(_) | payments::WalletData::CashappQr(_) - | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()), } } @@ -227,13 +220,8 @@ impl TryFrom<&api_models::payments::BankTransferData> for Shift4PaymentMethod { bank_transfer_data: &api_models::payments::BankTransferData, ) -> Result<Self, Self::Error> { match bank_transfer_data { - payments::BankTransferData::MultibancoBankTransfer { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()) - } - payments::BankTransferData::AchBankTransfer { .. } + payments::BankTransferData::MultibancoBankTransfer { .. } + | payments::BankTransferData::AchBankTransfer { .. } | payments::BankTransferData::SepaBankTransfer { .. } | payments::BankTransferData::BacsBankTransfer { .. } | payments::BankTransferData::PermataBankTransfer { .. } @@ -244,10 +232,9 @@ impl TryFrom<&api_models::payments::BankTransferData> for Shift4PaymentMethod { | payments::BankTransferData::DanamonVaBankTransfer { .. } | payments::BankTransferData::MandiriVaBankTransfer { .. } | payments::BankTransferData::Pix {} - | payments::BankTransferData::Pse {} => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + | payments::BankTransferData::Pse {} => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()), } } @@ -257,11 +244,8 @@ impl TryFrom<&api_models::payments::VoucherData> for Shift4PaymentMethod { type Error = Error; fn try_from(voucher_data: &api_models::payments::VoucherData) -> Result<Self, Self::Error> { match voucher_data { - payments::VoucherData::Boleto(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()), - payments::VoucherData::Efecty + payments::VoucherData::Boleto(_) + | payments::VoucherData::Efecty | payments::VoucherData::PagoEfectivo | payments::VoucherData::RedCompra | payments::VoucherData::RedPagos @@ -273,10 +257,9 @@ impl TryFrom<&api_models::payments::VoucherData> for Shift4PaymentMethod { | payments::VoucherData::MiniStop(_) | payments::VoucherData::FamilyMart(_) | payments::VoucherData::Seicomart(_) - | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()), } } @@ -286,15 +269,12 @@ impl TryFrom<&api_models::payments::GiftCardData> for Shift4PaymentMethod { type Error = Error; fn try_from(gift_card_data: &api_models::payments::GiftCardData) -> Result<Self, Self::Error> { match gift_card_data { - payments::GiftCardData::Givex(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", + payments::GiftCardData::Givex(_) | payments::GiftCardData::PaySafeCard {} => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) + .into()) } - .into()), - payments::GiftCardData::PaySafeCard {} => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()), } } } @@ -401,10 +381,9 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme | Some(payments::PaymentMethodData::Reward) | Some(payments::PaymentMethodData::Upi(_)) | Some(api::PaymentMethodData::CardToken(_)) - | None => Err(errors::ConnectorError::NotSupported { - message: "Flow".to_string(), - connector: "Shift4", - } + | None => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()), } } @@ -421,13 +400,8 @@ impl TryFrom<&payments::BankRedirectData> for PaymentMethodType { payments::BankRedirectData::BancontactCard { .. } | payments::BankRedirectData::Blik { .. } | payments::BankRedirectData::Trustly { .. } - | payments::BankRedirectData::Przelewy24 { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()) - } - payments::BankRedirectData::Bizum {} + | payments::BankRedirectData::Przelewy24 { .. } + | payments::BankRedirectData::Bizum {} | payments::BankRedirectData::Interac { .. } | payments::BankRedirectData::OnlineBankingCzechRepublic { .. } | payments::BankRedirectData::OnlineBankingFinland { .. } @@ -436,10 +410,9 @@ impl TryFrom<&payments::BankRedirectData> for PaymentMethodType { | payments::BankRedirectData::OpenBankingUk { .. } | payments::BankRedirectData::OnlineBankingFpx { .. } | payments::BankRedirectData::OnlineBankingThailand { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()) } }
2023-11-15T17:32:45Z
## 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 --> ### 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 Resolves #2860 ## 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)? --> No test cases required. As In this PR only error message have been changed from Not Supported error message to NotImplemented error message. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2e2dbe47156695beff6c0e4c800c0036fc426ed0
juspay/hyperswitch
juspay__hyperswitch-2858
Bug: [REFACTOR] : [Paypal] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index baf8f48279d..88595585fe1 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -396,11 +396,9 @@ fn get_payment_source( | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } - .into()) + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ))? } } } @@ -544,10 +542,9 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | api_models::payments::WalletData::WeChatPayQr(_) | api_models::payments::WalletData::CashappQr(_) | api_models::payments::WalletData::SwishQr(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ))? } }, api::PaymentMethodData::BankRedirect(ref bank_redirection_data) => { @@ -611,10 +608,9 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | api_models::payments::PaymentMethodData::Crypto(_) | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -629,10 +625,9 @@ impl TryFrom<&api_models::payments::CardRedirectData> for PaypalPaymentsRequest | api_models::payments::CardRedirectData::Benefit {} | api_models::payments::CardRedirectData::MomoAtm {} | api_models::payments::CardRedirectData::CardRedirect {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -651,10 +646,9 @@ impl TryFrom<&api_models::payments::PayLaterData> for PaypalPaymentsRequest { | api_models::payments::PayLaterData::WalleyRedirect {} | api_models::payments::PayLaterData::AlmaRedirect {} | api_models::payments::PayLaterData::AtomeRedirect {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -669,10 +663,9 @@ impl TryFrom<&api_models::payments::BankDebitData> for PaypalPaymentsRequest { | api_models::payments::BankDebitData::SepaBankDebit { .. } | api_models::payments::BankDebitData::BecsBankDebit { .. } | api_models::payments::BankDebitData::BacsBankDebit { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -696,10 +689,9 @@ impl TryFrom<&api_models::payments::BankTransferData> for PaypalPaymentsRequest | api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } | api_models::payments::BankTransferData::Pix {} | api_models::payments::BankTransferData::Pse {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -724,10 +716,9 @@ impl TryFrom<&api_models::payments::VoucherData> for PaypalPaymentsRequest { | api_models::payments::VoucherData::FamilyMart(_) | api_models::payments::VoucherData::Seicomart(_) | api_models::payments::VoucherData::PayEasy(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -740,10 +731,9 @@ impl TryFrom<&api_models::payments::GiftCardData> for PaypalPaymentsRequest { match value { api_models::payments::GiftCardData::Givex(_) | api_models::payments::GiftCardData::PaySafeCard {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } }
2023-11-15T16:31:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Refactored `NotSupported` Error calls to `NotImplemented` in the Paypal transformer. ### 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` --> Changes are here: `crates/router/src/connector/paypal/transformer.rs` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> These changes fix the open issue #2858. ## 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 any payment for Paypal connector for any PM which is not implemented, and see for the error message - it should be payment method not implemented ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
94cd7b689758a71e13a3eaa655335e658d13afc8
juspay/hyperswitch
juspay__hyperswitch-2855
Bug: [REFACTOR] : [Nuvei] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index c23114e2a96..3c9686c4e22 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -623,11 +623,9 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC { | api_models::enums::BankNames::TsbBank | api_models::enums::BankNames::TescoBank | api_models::enums::BankNames::UlsterBank => { - Err(errors::ConnectorError::NotSupported { - message: bank.to_string(), - connector: "Nuvei", - } - .into()) + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Nuvei"), + ))? } } } @@ -693,10 +691,9 @@ impl<F> bank_name.map(NuveiBIC::try_from).transpose()?, ) } - _ => Err(errors::ConnectorError::NotSupported { - message: "Bank Redirect".to_string(), - connector: "Nuvei", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Nuvei"), + ))?, }; Ok(Self { payment_option: PaymentOption {
2023-11-13T08:52:39Z
## 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 --> - Fix issue: #2855 - Changes to be made: update the error message - File changed: **```transformers.rs```** (crates/router/src/connector/nuvei/transformers.rs) ### 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)? --> ## Test Cases Check for BankRedirect which is not implemented, here we can check for Przelewy24 and we should get `notImplemented` error message. ``` "payment_method": "bank_redirect", "payment_method_type": "przelewy_24", "payment_method_data": { "bank_redirect": { "eps": { "billing_details": { "email": "jane@jones.com" } } } }, ``` ## 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` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f88eee7362be2cc3e8e8dc2bb7bfd263892ff01e
juspay/hyperswitch
juspay__hyperswitch-2844
Bug: [REFACTOR] : [Noon] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index ee06cd064be..8bb3a96a3ca 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -275,10 +275,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { | api_models::payments::WalletData::WeChatPayQr(_) | api_models::payments::WalletData::CashappQr(_) | api_models::payments::WalletData::SwishQr(_) => { - Err(errors::ConnectorError::NotSupported { - message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Noon", - }) + Err(errors::ConnectorError::NotImplemented( + conn_utils::get_unimplemented_payment_method_error_message("Noon"), + )) } }, api::PaymentMethodData::CardRedirect(_) @@ -293,10 +292,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { | api::PaymentMethodData::Voucher(_) | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Noon", - }) + Err(errors::ConnectorError::NotImplemented( + conn_utils::get_unimplemented_payment_method_error_message("Noon"), + )) } }?, Some(item.request.currency),
2023-11-11T20:02:31Z
## 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 --> ### 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? Make any payment for Noon connector for any PM which is not implemented, and see for the error message - it should be payment method not implemented ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable Resolve #2844
1828ea6187c46d9c18dc8a0b5224387403b998e2
juspay/hyperswitch
juspay__hyperswitch-2843
Bug: [REFACTOR] : [NMI] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index fcf35bfbe37..5b486aae600 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -494,10 +494,9 @@ impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod { | api_models::payments::WalletData::WeChatPayQr(_) | api_models::payments::WalletData::CashappQr(_) | api_models::payments::WalletData::SwishQr(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "nmi", - }) + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nmi"), + )) .into_report() } }, @@ -512,10 +511,9 @@ impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod { | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) | api::PaymentMethodData::GiftCard(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "nmi", - }) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nmi"), + )) .into_report(), } }
2023-11-11T20:00:09Z
## 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 --> ### 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? Make any payment for NMI for any PM which is not implemented, and see for the error message - it should be payment method not implemented <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable resolve #2843
db3d53ff1d8b42d107fafe7a6efe7ec9f155d5a0
juspay/hyperswitch
juspay__hyperswitch-2842
Bug: [REFACTOR] : [Multisafepay] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 1780b77379c..fb62643d667 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -262,10 +262,9 @@ impl TryFrom<utils::CardIssuer> for Gateway { utils::CardIssuer::Visa => Ok(Self::Visa), utils::CardIssuer::DinersClub | utils::CardIssuer::JCB - | utils::CardIssuer::CarteBlanche => Err(errors::ConnectorError::NotSupported { - message: issuer.to_string(), - connector: "Multisafe pay", - } + | utils::CardIssuer::CarteBlanche => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Multisafe pay"), + ) .into()), } }
2023-11-11T20:15:57Z
## 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 --> ### 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable resolve #2842
de8e31b70d9b3c11e268cd1deffa71918dc4270d
juspay/hyperswitch
juspay__hyperswitch-2841
Bug: [REFACTOR] : [Helcim] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index dc38b2eeb25..1a5a8baa7ee 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -143,10 +143,9 @@ impl TryFrom<&types::SetupMandateRouterData> for HelcimVerifyRequest { | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Helcim", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Helcim"), + ))? } } } @@ -225,10 +224,9 @@ impl TryFrom<&HelcimRouterData<&types::PaymentsAuthorizeRouterData>> for HelcimP | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.router_data.request.payment_method_data), - connector: "Helcim", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Helcim"), + ))?, } } }
2023-11-11T20:11:13Z
## 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 --> ### 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable Resolved #2841
bc79d522c30aa036378cf1e01354c422585cc226
juspay/hyperswitch
juspay__hyperswitch-2840
Bug: [REFACTOR] : [Forte] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 4bb354f6cda..56555a0d97e 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -54,10 +54,9 @@ impl TryFrom<utils::CardIssuer> for ForteCardType { utils::CardIssuer::Visa => Ok(Self::Visa), utils::CardIssuer::DinersClub => Ok(Self::DinersClub), utils::CardIssuer::JCB => Ok(Self::Jcb), - _ => Err(errors::ConnectorError::NotSupported { - message: issuer.to_string(), - connector: "Forte", - } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Forte"), + ) .into()), } } @@ -67,10 +66,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { if item.request.currency != enums::Currency::USD { - Err(errors::ConnectorError::NotSupported { - message: item.request.currency.to_string(), - connector: "Forte", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Forte"), + ))? } match item.request.payment_method_data { api_models::payments::PaymentMethodData::Card(ref ccard) => { @@ -114,10 +112,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Forte", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Forte"), + ))? } } }
2023-11-11T19:54:50Z
## 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 --> ### 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable Resolve #2840
bc79d522c30aa036378cf1e01354c422585cc226
juspay/hyperswitch
juspay__hyperswitch-2839
Bug: [REFACTOR] : [CryptoPay] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 3af604c786b..4102945b201 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -82,10 +82,9 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "CryptoPay", - }) + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("CryptoPay"), + )) } }?; Ok(cryptopay_request)
2023-11-11T19:51:04Z
## 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 --> ### 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` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable Resolve #2839
bc79d522c30aa036378cf1e01354c422585cc226
juspay/hyperswitch
juspay__hyperswitch-2838
Bug: [REFACTOR] : [Adyen] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 1eede78503b..aa5cd2ec695 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -752,10 +752,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingCzechRepublicBanks { api::enums::BankNames::KomercniBanka => Ok(Self::KB), api::enums::BankNames::CeskaSporitelna => Ok(Self::CS), api::enums::BankNames::PlatnoscOnlineKartaPlatnicza => Ok(Self::C), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -832,10 +831,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingPolandBanks { api_models::enums::BankNames::ToyotaBank => Ok(Self::ToyotaBank), api_models::enums::BankNames::VeloBank => Ok(Self::VeloBank), api_models::enums::BankNames::ETransferPocztowy24 => Ok(Self::ETransferPocztowy24), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -884,10 +882,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingSlovakiaBanks { api::enums::BankNames::SporoPay => Ok(Self::Sporo), api::enums::BankNames::TatraPay => Ok(Self::Tatra), api::enums::BankNames::Viamo => Ok(Self::Viamo), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -914,10 +911,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingFpxIssuer { api::enums::BankNames::RhbBank => Ok(Self::FpxRhb), api::enums::BankNames::StandardCharteredBank => Ok(Self::FpxScb), api::enums::BankNames::UobBank => Ok(Self::FpxUob), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -931,10 +927,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingThailandIssuer { api::enums::BankNames::KrungThaiBank => Ok(Self::Krungthaibank), api::enums::BankNames::TheSiamCommercialBank => Ok(Self::Siamcommercialbank), api::enums::BankNames::KasikornBank => Ok(Self::Kbank), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -1087,10 +1082,9 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer { | enums::BankNames::Yoursafe | enums::BankNames::N26 | enums::BankNames::NationaleNederlanden - | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -1484,10 +1478,9 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> { api_models::enums::BankNames::VolkskreditbankAg => { Self("4a0a975b-0594-4b40-9068-39f77b3a91f9") } - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, }) } } @@ -1591,10 +1584,9 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))? } }, } @@ -1893,10 +1885,9 @@ impl<'a> TryFrom<&api_models::payments::BankDebitData> for AdyenPaymentMethod<'a }, ))), payments::BankDebitData::BecsBankDebit { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) .into()) } } @@ -1944,10 +1935,9 @@ impl<'a> TryFrom<&api_models::payments::VoucherData> for AdyenPaymentMethod<'a> payments::VoucherData::Efecty | payments::VoucherData::PagoEfectivo | payments::VoucherData::RedCompra - | payments::VoucherData::RedPagos => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - } + | payments::VoucherData::RedPagos => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) .into()), } } @@ -2131,10 +2121,9 @@ impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> { | payments::WalletData::GooglePayThirdPartySdk(_) | payments::WalletData::PaypalSdk(_) | payments::WalletData::WeChatPayQr(_) - | payments::WalletData::CashappQr(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - } + | payments::WalletData::CashappQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) .into()), } } @@ -2264,11 +2253,12 @@ impl<'a> check_required_field(billing_address, "billing")?; Ok(AdyenPaymentMethod::Atome) } - payments::PayLaterData::KlarnaSdk { .. } => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", + payments::PayLaterData::KlarnaSdk { .. } => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) + .into()) } - .into()), } } } @@ -2428,10 +2418,9 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)> } payments::BankRedirectData::Interac { .. } | payments::BankRedirectData::Przelewy24 { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) .into()) } }
2023-11-11T19:43:05Z
## 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 --> ### 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? Test a Payment Method which is not implemented It should give Not implemented error This is an Crypto payment request. ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_data": { "crypto": {} }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "profile_id": "pro_16j8JOCurimvr2XXG9EE" } ``` This is a Payment Method which is not implemented for adyen ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable Resolve #2838
708cce926125a29b406db48cf0ebd35b217927d4
juspay/hyperswitch
juspay__hyperswitch-2836
Bug: [REFACTOR] : [ACI] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 9cfb657bdca..8eea6dbb4d5 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -410,10 +410,9 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.router_data.payment_method), - connector: "Aci", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Aci"), + ))?, } } }
2023-11-11T07:35:43Z
## 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 --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context ## How did you test it? Manual checking ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable Fixes [2836](https://github.com/juspay/hyperswitch/issues/2836)
bc79d522c30aa036378cf1e01354c422585cc226