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(webhook): add frm webhook support #4662

Merged
merged 20 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
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/api_models/src/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,3 +590,8 @@ pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnector
pub fn convert_authentication_connector(connector_name: &str) -> Option<AuthenticationConnectors> {
AuthenticationConnectors::from_str(connector_name).ok()
}

#[cfg(feature = "frm")]
pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> {
FrmConnectors::from_str(connector_name).ok()
}
6 changes: 6 additions & 0 deletions crates/api_models/src/webhooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub enum IncomingWebhookEvent {
MandateRevoked,
EndpointVerification,
ExternalAuthenticationARes,
FrmApproved,
FrmRejected,
}

pub enum WebhookFlow {
Expand All @@ -50,6 +52,7 @@ pub enum WebhookFlow {
BankTransfer,
Mandate,
ExternalAuthentication,
FraudCheck,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
Expand Down Expand Up @@ -119,6 +122,9 @@ impl From<IncomingWebhookEvent> for WebhookFlow {
IncomingWebhookEvent::SourceChargeable
| IncomingWebhookEvent::SourceTransactionCreated => Self::BankTransfer,
IncomingWebhookEvent::ExternalAuthenticationARes => Self::ExternalAuthentication,
IncomingWebhookEvent::FrmApproved | IncomingWebhookEvent::FrmRejected => {
Self::FraudCheck
}
}
}
}
Expand Down
125 changes: 102 additions & 23 deletions crates/router/src/connector/riskified.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,46 @@ pub mod transformers;
use std::fmt::Debug;

#[cfg(feature = "frm")]
use common_utils::request::RequestContent;
use error_stack::{report, ResultExt};
use base64::Engine;
#[cfg(feature = "frm")]
use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
#[cfg(feature = "frm")]
use error_stack::ResultExt;
#[cfg(feature = "frm")]
use masking::{ExposeInterface, PeekInterface};
#[cfg(feature = "frm")]
use ring::hmac;
#[cfg(feature = "frm")]
use transformers as riskified;

#[cfg(feature = "frm")]
use super::utils::FrmTransactionRouterDataRequest;
use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
headers,
services::{self, request, ConnectorIntegration, ConnectorValidation},
services::{self, ConnectorIntegration, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
};
#[cfg(feature = "frm")]
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
headers,
services::request,
types::{
api::fraud_check as frm_api, domain, fraud_check as frm_types, ErrorResponse, Response,
},
utils::BytesExt,
};

#[derive(Debug, Clone)]
pub struct Riskified;

impl Riskified {
#[cfg(feature = "frm")]
pub fn generate_authorization_signature(
&self,
auth: &riskified::RiskifiedAuthType,
Expand All @@ -53,6 +64,7 @@ impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Ri
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
#[cfg(feature = "frm")]
fn build_headers(
&self,
req: &types::RouterData<Flow, Request, Response>,
Expand Down Expand Up @@ -122,7 +134,7 @@ impl ConnectorCommon for Riskified {
Ok(ErrorResponse {
status_code: res.status_code,
attempt_status: None,
code: crate::consts::NO_ERROR_CODE.to_string(),
code: consts::NO_ERROR_CODE.to_string(),
message: response.error.message.clone(),
reason: None,
connector_transaction_id: None,
Expand Down Expand Up @@ -268,11 +280,7 @@ impl
self.base_url(connectors),
"/checkout_denied"
)),
Some(true) => Ok(format!("{}{}", self.base_url(connectors), "/decision")),
None => Err(errors::ConnectorError::FlowNotSupported {
flow: "Transaction".to_owned(),
connector: req.connector.to_string(),
})?,
_ => Ok(format!("{}{}", self.base_url(connectors), "/decision")),
}
}

Expand All @@ -286,14 +294,10 @@ impl
let req_obj = riskified::TransactionFailedRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
Some(true) => {
_ => {
let req_obj = riskified::TransactionSuccessRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
None => Err(errors::ConnectorError::FlowNotSupported {
flow: "Transaction".to_owned(),
connector: req.connector.to_owned(),
})?,
}
}

Expand Down Expand Up @@ -545,26 +549,101 @@ impl frm_api::FraudCheckFulfillment for Riskified {}
#[cfg(feature = "frm")]
impl frm_api::FraudCheckRecordReturn for Riskified {}

#[cfg(feature = "frm")]
#[async_trait::async_trait]
impl api::IncomingWebhook for Riskified {
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 header_value =
connector_utils::get_header_key_value("x-riskified-hmac-sha256", request.headers)?;
Ok(header_value.as_bytes().to_vec())
}

async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: domain::MerchantConnectorAccount,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_account,
connector_label,
merchant_connector_account,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

let message = self
.get_webhook_source_verification_message(
request,
&merchant_account.merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret);
let signed_message = hmac::sign(&signing_key, &message);
let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref());
Ok(payload_sign.as_bytes().eq(&signature))
}

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> {
Ok(request.body.to_vec())
}

fn get_webhook_object_reference_id(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
let resource: riskified::RiskifiedWebhookBody = request
.body
.parse_struct("RiskifiedWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(resource.id),
))
}

fn get_webhook_event_type(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
let resource: riskified::RiskifiedWebhookBody = request
.body
.parse_struct("RiskifiedWebhookBody")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(api::IncomingWebhookEvent::from(resource.status))
}

fn get_webhook_resource_object(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
let resource: riskified::RiskifiedWebhookBody = request
.body
.parse_struct("RiskifiedWebhookBody")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(resource))
}
}
29 changes: 26 additions & 3 deletions crates/router/src/connector/riskified/transformers/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
},
core::{errors, fraud_check::types as core_types},
types::{
self, api::Fulfillment, fraud_check as frm_types, storage::enums as storage_enums,
self, api, api::Fulfillment, fraud_check as frm_types, storage::enums as storage_enums,
ResponseId, ResponseRouterData,
},
};
Expand Down Expand Up @@ -142,8 +142,9 @@ impl TryFrom<&frm_types::FrmCheckoutRouterData> for RiskifiedPaymentsCheckoutReq
field_name: "frm_metadata",
})?
.parse_value("Riskified Metadata")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;

.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "frm_metadata",
})?;
let billing_address = payment_data.get_billing()?;
let shipping_address = payment_data.get_shipping_address_with_phone_number()?;
let address = payment_data.get_billing_address()?;
Expand Down Expand Up @@ -606,3 +607,25 @@ fn get_fulfillment_status(
core_types::FulfillmentStatus::PARTIAL | core_types::FulfillmentStatus::REPLACEMENT => None,
}
}

#[derive(Debug, Clone, Deserialize, Serialize)]

pub struct RiskifiedWebhookBody {
pub id: String,
pub status: RiskifiedWebhookStatus,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum RiskifiedWebhookStatus {
Approved,
Declined,
}

impl From<RiskifiedWebhookStatus> for api::IncomingWebhookEvent {
fn from(value: RiskifiedWebhookStatus) -> Self {
match value {
RiskifiedWebhookStatus::Declined => Self::FrmRejected,
RiskifiedWebhookStatus::Approved => Self::FrmApproved,
}
}
}
Loading
Loading