Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): Add ability to verify connector credentials before integrating the connector #2986

Merged
merged 19 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
275b622
feat: Add ability to verify connector creds before integrating the co…
ThisIsMani Nov 27, 2023
48567a0
refactor: add separate request for verify_connector
ThisIsMani Nov 27, 2023
7974007
Merge branch 'main' into verify-connector
ThisIsMani Nov 27, 2023
57ed4f3
chore: run formatter
hyperswitch-bot[bot] Nov 27, 2023
2dc4b03
refactor: use ConnectorAuthType enum in the request body instead of V…
ThisIsMani Nov 28, 2023
ef1beb9
Merge branch 'main' of https://github.com/juspay/hyperswitch into ver…
ThisIsMani Nov 28, 2023
a43e263
chore: run formatter
hyperswitch-bot[bot] Nov 28, 2023
c23218f
refactor: move connector specific logic to their corresponding files
ThisIsMani Nov 28, 2023
7b0ccfb
refactor: add ConnectorAuthType in api_models
ThisIsMani Nov 28, 2023
22df5da
Merge branch 'main' of https://github.com/juspay/hyperswitch into ver…
ThisIsMani Nov 28, 2023
7f7c488
refactor: make test_mode None in router_data construction
ThisIsMani Nov 28, 2023
db50325
refactor: remove unused imports
ThisIsMani Nov 28, 2023
c99c0cc
fix: clippy lints
ThisIsMani Nov 28, 2023
cce31a5
fix: format
ThisIsMani Nov 28, 2023
2f8745b
Merge branch 'main' of https://github.com/juspay/hyperswitch into ver…
ThisIsMani Nov 28, 2023
cb204f1
refactor: replace Into to ForeignFrom for ConnectorAuthType
ThisIsMani Nov 29, 2023
b5d183d
chore: run formatter
hyperswitch-bot[bot] Nov 29, 2023
45cd592
Merge branch 'main' of https://github.com/juspay/hyperswitch into ver…
ThisIsMani Nov 29, 2023
1d057a0
Merge branch 'main' into verify-connector
ThisIsMani Nov 30, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/router/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,8 @@ pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes
pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days

pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin";

#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant";
2 changes: 2 additions & 0 deletions crates/router/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,6 @@ pub mod user;
pub mod utils;
#[cfg(all(feature = "olap", feature = "kms"))]
pub mod verification;
#[cfg(feature = "olap")]
pub mod verify_connector;
pub mod webhooks;
63 changes: 63 additions & 0 deletions crates/router/src/core/verify_connector.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use api_models::enums::Connector;
use error_stack::{IntoReport, ResultExt};

use crate::{
connector,
core::errors,
services,
types::{
api,
api::verify_connector::{self as types, VerifyConnector},
},
utils::verify_connector as utils,
AppState,
};

pub async fn verify_connector_credentials(
state: AppState,
req: types::VerifyConnectorRequest,
) -> errors::RouterResponse<()> {
let boxed_connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&req.connector_name.to_string(),
api::GetToken::Connector,
None,
)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?;

let card_details = utils::get_test_card_details(req.connector_name)?
.ok_or(errors::ApiErrorResponse::FlowNotSupported {
flow: "Verify credentials".to_string(),
connector: req.connector_name.to_string(),
})
.into_report()?;

match req.connector_name {
Connector::Stripe => {
connector::Stripe::verify(
&state,
types::VerifyConnectorData {
connector: *boxed_connector.connector,
connector_auth: req.connector_account_details,
card_details,
},
)
.await
}
Connector::Paypal => connector::Paypal::get_access_token(
&state,
types::VerifyConnectorData {
connector: *boxed_connector.connector,
connector_auth: req.connector_account_details,
card_details,
},
)
.await
.map(|_| services::ApplicationResponse::StatusOk),
_ => Err(errors::ApiErrorResponse::FlowNotSupported {
flow: "Verify credentials".to_string(),
connector: req.connector_name.to_string(),
})
.into_report(),
}
}
2 changes: 2 additions & 0 deletions crates/router/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ pub mod routing;
pub mod user;
#[cfg(all(feature = "olap", feature = "kms"))]
pub mod verification;
#[cfg(feature = "olap")]
pub mod verify_connector;
pub mod webhooks;

pub mod locker_migration;
Expand Down
6 changes: 6 additions & 0 deletions crates/router/src/routes/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ use super::{cache::*, health::*};
use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*};
#[cfg(feature = "oltp")]
use super::{ephemeral_key::*, payment_methods::*, webhooks::*};
#[cfg(feature = "olap")]
use crate::routes::verify_connector::payment_connector_verify;
use crate::{
configs::settings,
db::{StorageImpl, StorageInterface},
Expand Down Expand Up @@ -507,6 +509,10 @@ impl MerchantConnectorAccount {
use super::admin::*;

route = route
.service(
web::resource("/connectors/verify")
.route(web::post().to(payment_connector_verify)),
)
.service(
web::resource("/{merchant_id}/connectors")
.route(web::post().to(payment_connector_create))
Expand Down
4 changes: 3 additions & 1 deletion crates/router/src/routes/lock_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,9 @@ impl From<Flow> for ApiIdentifier {
| Flow::GsmRuleUpdate
| Flow::GsmRuleDelete => Self::Gsm,

Flow::UserConnectAccount | Flow::ChangePassword => Self::User,
Flow::UserConnectAccount | Flow::ChangePassword | Flow::VerifyPaymentConnector => {
Self::User
}
}
}
}
28 changes: 28 additions & 0 deletions crates/router/src/routes/verify_connector.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};

use super::AppState;
use crate::{
core::{api_locking, verify_connector},
services::{self, authentication as auth, authorization::permissions::Permission},
types::api::verify_connector::VerifyConnectorRequest,
};

#[instrument(skip_all, fields(flow = ?Flow::VerifyPaymentConnector))]
pub async fn payment_connector_verify(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<VerifyConnectorRequest>,
) -> HttpResponse {
let flow = Flow::VerifyPaymentConnector;
Box::pin(services::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _: (), req| verify_connector::verify_connector_credentials(state, req),
&auth::JWTAuth(Permission::MerchantConnectorAccountWrite),
api_locking::LockAction::NotApplicable,
))
.await
}
2 changes: 2 additions & 0 deletions crates/router/src/types/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub mod payments;
pub mod payouts;
pub mod refunds;
pub mod routing;
#[cfg(feature = "olap")]
pub mod verify_connector;
pub mod webhooks;

use std::{fmt::Debug, str::FromStr};
Expand Down
192 changes: 192 additions & 0 deletions crates/router/src/types/api/verify_connector.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
pub mod paypal;
pub mod stripe;

use api_models::enums as api_enums;
use common_utils::events::{ApiEventMetric, ApiEventsType};
use error_stack::{IntoReport, ResultExt};
use router_env as env;

use crate::{
consts,
core::errors,
services,
services::ConnectorIntegration,
types::{self, api, storage::enums as storage_enums},
AppState,
};

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct VerifyConnectorRequest {
pub connector_name: api_enums::Connector,
pub connector_account_details: types::ConnectorAuthType,
}

common_utils::impl_misc_api_event_type!(VerifyConnectorRequest);

#[derive(Clone, Debug)]
pub struct VerifyConnectorData {
pub connector: &'static (dyn types::api::Connector + Sync),
pub connector_auth: types::ConnectorAuthType,
pub card_details: api::Card,
}

impl VerifyConnectorData {
fn get_payment_authorize_data(&self) -> types::PaymentsAuthorizeData {
types::PaymentsAuthorizeData {
payment_method_data: api::PaymentMethodData::Card(self.card_details.clone()),
email: None,
amount: 1000,
confirm: true,
currency: storage_enums::Currency::USD,
mandate_id: None,
webhook_url: None,
customer_id: None,
off_session: None,
browser_info: None,
session_token: None,
order_details: None,
order_category: None,
capture_method: None,
enrolled_for_3ds: false,
router_return_url: None,
surcharge_details: None,
setup_future_usage: None,
payment_experience: None,
payment_method_type: None,
statement_descriptor: None,
setup_mandate_details: None,
complete_authorize_url: None,
related_transaction_id: None,
statement_descriptor_suffix: None,
}
}

fn get_router_data<F, R1, R2>(
&self,
request_data: R1,
access_token: Option<types::AccessToken>,
) -> types::RouterData<F, R1, R2> {
let attempt_id =
common_utils::generate_id_with_default_len(consts::VERIFY_CONNECTOR_ID_PREFIX);
types::RouterData {
flow: std::marker::PhantomData,
status: storage_enums::AttemptStatus::Started,
request: request_data,
response: Err(errors::ApiErrorResponse::InternalServerError.into()),
connector: self.connector.id().to_string(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
test_mode: Some(!matches!(env::which(), env::Env::Production)),
return_url: None,
attempt_id: attempt_id.clone(),
description: None,
customer_id: None,
merchant_id: consts::VERIFY_CONNECTOR_MERCHANT_ID.to_string(),
reference_id: None,
access_token,
session_token: None,
payment_method: storage_enums::PaymentMethod::Card,
amount_captured: None,
preprocessing_id: None,
payment_method_id: None,
connector_customer: None,
connector_auth_type: self.connector_auth.clone(),
connector_meta_data: None,
payment_method_token: None,
connector_api_version: None,
recurring_mandate_payment_data: None,
connector_request_reference_id: attempt_id,
address: types::PaymentAddress {
shipping: None,
billing: None,
},
payment_id: common_utils::generate_id_with_default_len(
consts::VERIFY_CONNECTOR_ID_PREFIX,
),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
}
}
}

#[async_trait::async_trait]
pub trait VerifyConnector {
async fn verify(
state: &AppState,
connector_data: VerifyConnectorData,
) -> errors::RouterResponse<()> {
let authorize_data = connector_data.get_payment_authorize_data();
let access_token = Self::get_access_token(state, connector_data.clone()).await?;
let router_data = connector_data.get_router_data(authorize_data, access_token);

let request = connector_data
.connector
.build_request(&router_data, &state.conf.connectors)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment request cannot be built".to_string(),
})?
.ok_or(errors::ApiErrorResponse::InternalServerError)?;

let response = services::call_connector_api(&state.to_owned(), request)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;

match response {
Ok(_) => Ok(services::ApplicationResponse::StatusOk),
Err(error_response) => {
Self::handle_payment_error_response::<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>(connector_data.connector, error_response)
.await
}
}
}

async fn get_access_token(
_state: &AppState,
_connector_data: VerifyConnectorData,
) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> {
// AccessToken is None for the connectors without the AccessToken Flow.
// If a connector has that, then it should override this implementation.
Ok(None)
}

async fn handle_payment_error_response<F, R1, R2>(
connector: &(dyn types::api::Connector + Sync),
error_response: types::Response,
) -> errors::RouterResponse<()>
where
dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
{
let error = connector
.get_error_response(error_response)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
})
.into_report()
}

async fn handle_access_token_error_response<F, R1, R2>(
connector: &(dyn types::api::Connector + Sync),
error_response: types::Response,
) -> errors::RouterResult<Option<types::AccessToken>>
where
dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
{
let error = connector
.get_error_response(error_response)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
})
.into_report()
}
}
Loading
Loading